gpt4 book ai didi

python - Tkinter Filedialog.askopenfilename 迭代

转载 作者:行者123 更新时间:2023-12-01 08:46:01 27 4
gpt4 key购买 nike

我正在开发程序来加载文件并使用这些加载的文件执行一些计算。

为此,我编写了一个简单的迭代代码来加载 tkinter 变量。窗口、标签、条目和按钮位置已经完成。到目前为止我的代码是:

import tkinter as tk
from tkinter import ttk, filedialog

LARGE_FONT = ("Arial", 12)
MEDIUM_FONT = ("Arial", 11)
REGULAR_FONT = ("Arial", 10)

text_z = ["Select file 1", "Select the file 2", "Select file 3", "Select file 4"]

window=tk.Tk()

def click():
z = tk.filedialog.askopenfilename(initialdir = "/",title = "Select file", filetypes = ( ("Excel file", "*.xlsx"), ("All files", "*.*") ) )
a[i-2].insert(tk.END, z)
z[i] = a[i-2].get()

##Main program
#There is an image I will add at the end on row=0
ttk.Label(window, text="file load", font = LARGE_FONT, background = "white").grid(row=1, column=1, columnspan=3, padx=20, pady = 10, sticky="W")

a = [tk.StringVar(window) for i in range(len(text_z))]

for i in range(2,len(text_z)+2):
Label_z = ttk.Label(window, text=text_z[i-2], background="white").grid(row= 2*i, column=0,columnspan=3, padx=10, pady=2, sticky="W")
a[i-2] = ttk.Entry(window, width=60, background="gray")
a[i-2].grid(row= 2*i+1, column=0, columnspan=3, padx=10, sticky="WE")
ttk.Button(window, text="Search", width=10, command=click).grid(row= 2*i+1, column=3, padx=5, sticky="W")

window.mainloop()

我的问题出在点击按钮上。它应该在单击期间运行askopenfilename,获取文件路径并显示在输入框中,但所有按钮都将其定向到最后创建的输入框。

有人可以帮我解决这个问题吗?

非常感谢!

最佳答案

Lambda 来救援。人们需要知道要更新的正确按钮-条目对。因此,按下按钮时传递相应索引的值。

import tkinter as tk
from tkinter import ttk, filedialog

LARGE_FONT = ("Arial", 12)
MEDIUM_FONT = ("Arial", 11)
REGULAR_FONT = ("Arial", 10)

text_z = ["Select file 1", "Select the file 2", "Select file 3", "Select file 4"]

window=tk.Tk()

def click(m):
z = tk.filedialog.askopenfilename(initialdir = "~",title = "Select file", filetypes = ( ("Text files", "*.txt"), ("All files", "*.*") ) )
a[m].insert(tk.END, z)

ttk.Label(window, text="file load", font = LARGE_FONT, background = "white").grid(row=1, column=1, columnspan=3, padx=20, pady = 10, sticky="W")

a = [None for i in range(len(text_z))]

for i in range(2,len(text_z)+2):
Label_z = ttk.Label(window, text=text_z[i-2], background="white").grid(row= 2*i, column=0,columnspan=3, padx=10, pady=2, sticky="W")
a[i-2] = ttk.Entry(window, width=60, background="gray")
a[i-2].grid(row= 2*i+1, column=0, columnspan=3, padx=10, sticky="WE")
ttk.Button(window, text="Search", width=10, command=lambda m=i-2:click(m)).grid(row= 2*i+1, column=3, padx=5, sticky="W")

window.mainloop()

enter image description here

关于python - Tkinter Filedialog.askopenfilename 迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53300739/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com