无法获取 StringVar 来更新标签

Cannot get StringVar to update Label

我快要发疯了,试图通过 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()

您需要提供参数 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 is associated with a Tkinter variable (usually a StringVar) with the label. If the variable is changed, the label text is updated.