Search code examples
pythonpython-3.xtkintertkinter-texttkinter-label

Cannot get StringVar to update Label


I'm going nuts trying to get this label updated via StringVar. I've read over millions of answers online, watched multiple tutorials and still can't get it to update the label when I run the program. What am I missing?

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


Solution

  • You need to provide parameter textvariable=save_diretory to actually tell Label to reflect the changes made to the StringVar()

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

    According to 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.