具有动态tkinter标签,无StringV

2024-04-24 23:52:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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()

Tags: textname目录fordefplacebuttonroot