我对python很陌生,并试图动态地将按钮添加到GUI上,并在框架上显示相应的标签,这样可行。但是,当我点击我的按钮打开目录选择器后,我遇到了问题,标签不会根据新路径更新,因为textvariable只接受StringVar,而我使用字典来跟踪所有动态创建的按钮及其路径(不是StringVar)。除非有某种方法可以将正常的字符串强制转换为StringVar吗?
我希望我解释得很清楚。
这是我可怕的代码,因为我只是想看看一切是如何运作的。基本上,这个程序应该包含一个起始目录,然后其他目录就是将起始目录复制到的目录。虽然我没有进入实际的保存部分。
from tkinter import *
dirID = []
dirMap = {}
dirAmt = 0
def getDirName():
dirName1.set(filedialog.askdirectory())
def getSaveDirName(event):
dirMap[event.widget] = filedialog.askdirectory()
def strToStringVar(name):
temp = StringVar()
temp.set(name)
return temp
def AddDir():
global dirAmt
global dirID
b = Button(mainFrame, text = "Directory" + str(dirAmt))
dirMap[b] = filedialog.askdirectory()
b.bind("<Button-1>", getSaveDirName)
b.place(x=10,y=(100+(60*dirAmt)))
name = StringVar()
name.set(dirMap[b])
l = Label(mainFrame, textvariable = name)
l.place(x=10,y=(130+(60*dirAmt)))
dirID.append(b)
dirAmt = dirAmt + 1
update(self)
def save():
for i in range (0,dirAmt):
print (dirMap[dirID[i]])
root=Tk()
root.title("File Copier")
mainFrame = Frame(root, width = 600, height = 500)
mainFrame.pack()
#Variables
dirName1 = StringVar()
#GUI
GetDirLabel = Label(mainFrame, text="Directory to copy:")
GetDirButton = Button(mainFrame, text = "Select Directory", command = getDirName)#Button for choosing directory
DirGetPathLabel = Label(mainFrame, textvariable=dirName1)#Label for chosen directory
SaveToLabel = Label(mainFrame, text="Directories to copy to:")
AddDirbtnButton = Button(mainFrame, text = "Add more directories", command = AddDir)#Button for Adding directory
SaveButton = Button(mainFrame, text = "Save", command = save)
GetDirLabel.place(x = 0, y = 10)
GetDirButton.place(x = 100, y=8)
DirGetPathLabel.place(x = 5, y = 45)
SaveToLabel.place(x = 0, y = 70)
AddDirbtnButton.place(x = 130, y = 68)
SaveButton.place(x = 300, y = 68)
root.mainloop()