0

我要疯了,试图通过 StringVar 更新这个标签。我已经在线阅读了数百万个答案,观看了多个教程,但在我运行程序时仍然无法更新标签。我错过了什么?

from os import name
import tkinter
import tkinter.filedialog as fd
from tkinter.constants import W
top = tkinter.Tk()

top.wm_title("NFT Generator")

L1 = tkinter.Label(top, text="Name your nft:")
L1.grid(row = 0, column = 0, sticky = W, pady = 2)
E1 = tkinter.Entry(top, bd =5)
E1.grid(row = 0, column = 1, sticky = W, pady = 2)

L2 = tkinter.Label(top, text="Choose a file type (PNG is preferred):",)
L2.grid(row = 1, column = 0, sticky = W, pady = 2)

variable = tkinter.StringVar(top)
variable.set(".png") # default value

OM = tkinter.OptionMenu(top, variable, ".png", ".jpg", ".jpeg", ".gif", ".bmp")
OM.grid(row = 1, column = 1, sticky = W, pady = 2)

L3 = tkinter.Label(top, text="Choose where you want to save your NFTs:")
L3.grid(row = 2, column = 0, sticky = W, pady = 2)

save_directory = tkinter.StringVar(top)
save_directory.set("knock, knock")

def callback():
    fd.askdirectory()
    save_directory.set("hello")
    top.update()

L4 = tkinter.Label(top, text=save_directory.get())
L4.grid(row = 2, column = 2, sticky = W, pady = 2)

tkinter.Button(text='Click to Open Folder', 
       command=callback).grid(row = 2, column = 1, sticky = W, pady = 2)

top.mainloop()

4

1 回答 1

0

您需要提供参数textvariable=save_diretory来实际告知Label以反映对StringVar()

L4 = tkinter.Label(top, text=save_directory.get(),textvariable=save_directory)
L4.grid(row = 2, column = 2, sticky = W, pady = 2)

根据Geeks for Geeks

textvariable与带有标签的Tkinter变量(通常是 a )相关联。StringVar如果变量更改,标签文本会更新。

于 2021-08-05T03:06:48.927 回答