0

I'm trying to update the Tkinter label on click of the button. Doesn't work when I click the button.

Here's the code:

valid = tk.StringVar()
valid.set("Not signed in")


validtext = tk.Label(root, text=valid.get(), font="Arial").grid(row=5, column=1)

testbtn_txt = tk.StringVar()
testbtn = tk.Button(root, textvariable=testbtn_txt, command=lambda:testfunc(), font="Arial", bg="#ff0000", fg="white", height=1, width=10)
testbtn_txt.set("Test")
testbtn.grid(row=3, column=1)

def testfunc():
    valid.set("Signed in")
    validtext.update()

What am I doing wrong? :( Thanks for help.

Cassano
  • 253
  • 5
  • 36
  • 1
    `text=valid.get()` retrieves the value from `valid` *at that exact moment in time*, and sets that as the text of the Label - there's no ongoing connection between the StringVar and the Label. To do something like that, you use `textvariable=valid` instead - just like you did for the Button. – jasonharper Dec 14 '21 at 18:05
  • Can you give me a clue how? I am new. :( When I change that to textvariable=valid then it doesn't show "Not signed in" - instead it shows PY_VAR0. – Cassano Dec 14 '21 at 18:21
  • 1
    That looks like you did `text=valid`, rather than `textvariable=`. – jasonharper Dec 14 '21 at 18:42
  • Please define what "doesn't work" means. – Bryan Oakley Dec 14 '21 at 19:15

1 Answers1

0

Thank you, @jasonharper. I changed to textvariable=valid and it worked.

The following needed changing:

validtext = tk.Label(root, text=valid.get(), font="Arial").grid(row=5, column=1)

to

validtext = tk.Label(root, textvariable=valid, font="Arial").grid(row=5, column=1)
Cassano
  • 253
  • 5
  • 36