使用tkinter定义函数或类来浏览和列出多个目录



我想创建一个具有适当格式的函数或类来创建文本标签、输入字段和按钮。该按钮允许我浏览目录,并用所选目录填充条目字段。我的代码允许我完成大部分工作,但是目录总是填充在最后一个输入字段中,而不是按钮所指的字段中

我是tkinter和GUI的新手,所以很抱歉,如果这是一个简单的解决方案,我认为问题在于root.name.set引用了上次调用的函数。

from tkinter import *
from tkinter import filedialog
def askdirectory():
dirname = filedialog.askdirectory()
root.name.set(dirname)

def dirField(root, label, rowNum):
text = StringVar()
text.set(label)
dirText = Label(root, textvariable = text, height =4)
dirText.grid(row = rowNum, column = 1)
dirBut = Button(root, text = 'Browse', command = askdirectory)
dirBut.grid(row = rowNum, column = 3)
root.name = StringVar()
adDir = Entry(root,textvariable = root.name, width = 100)
adDir.grid(row = rowNum, column = 2)

if __name__ == '__main__':
root = Tk()
root.geometry('1000x750')
adText = "Select directory of Ads"
userText = "Select directory of User credentials"
adField = dirField(root, adText, 1)
userField = dirField(root, userText, 2)
root.mainloop()

您应该意识到,您需要让每个Entry都有自己的textvariable。否则,它们将重叠。看看我的代码,它应该会让你开始。

from tkinter import *
from tkinter import filedialog
path = [None, None] # Fill it with the required number of filedialogs
def askdirectory(i):
dirname = filedialog.askdirectory()
path[i].set(dirname)

def dirField(root, label, rowNum, i):
dirText = Label(root, text=label)
dirText.grid(row=rowNum, column=0)
dirBut = Button(root, text='Browse', command=lambda: askdirectory(i))
dirBut.grid(row=rowNum, column=2)
path[i] = StringVar()
adDir = Entry(root, textvariable=path[i], width=50)
adDir.grid(row=rowNum, column=1)

if __name__ == '__main__':
root = Tk()
adText = "Select directory of Ads"
userText = "Select directory of User credentials"
adField = dirField(root, adText, 0, 0)
userField = dirField(root, userText, 1, 1)
root.mainloop()

最新更新