我想创建一个具有正确格式的函数或类,以创建文本标签,输入字段和按钮。该按钮将允许我浏览我的目录,并使用所选目录填充输入字段。我拥有的代码可以完成大部分操作,但是目录始终填充在最后一个输入字段中,而不是按钮所引用的目录中。
我对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()
答案 0 :(得分:1)
您应该意识到,每个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()