1

Im trying to make a simple GUI with Tkinker that, when you press a button it adds 1 to the text on a label. However, the label simply remains at 0. Is there a way I can refresh it so it stays up-to-date?

heres what i have so far:

from Tkinter import * clicks = 0 def click(): global clicks global Window clicks += 1 print 'ok', clicks def close_window(): global Window Window.destroy() Window = Tk() Number = Label(text = clicks) close = Button(Window , text='exit' , command = close_window) button = Button(Window,text = 'clickme' ,command = click) button.pack() close.pack() Number.pack() Window.mainloop() 

2 Answers 2

3

clicks += 1 only changes the variable clicks.

Use Label.config(text=...) or Label['text'] = ... to change the label text.

def click(): global clicks clicks += 1 Number.config(text=clicks) # <------ print 'ok', clicks 
Sign up to request clarification or add additional context in comments.

Comments

0

You almost have it, but for your label you don't want to use "text", you want "textvariable". However, this takes a StringVar as a variable, which forces a little bit of busywork:

Window = Tk() strclicks = StringVar() Number = Label(textvariable=clicks) 

and within click():

 clicks += 1 strclicks.set(clicks) 

Using "text" evaluates the variable at creation; "textvariable" updates the label when the variable updates.

2 Comments

For such a simple problem, IMO a textvariable is overkill. Whether with or without a textvariable, updating requires a function call (either widget.configure or variable.set). The use of a textvariable requires an extra object while providing no real advantage over just directly configuring the label.
@BryanOakley That's a reasonable position. Before I started on Python, I was a long-time Tcl user, so my attitude towards textvariable is influenced by that. In Tcl, the variable doesn't need to be a special object and it just works, no call necessary. I actually wrote my answer up like that before the other answer went live, went to test it as confirmation, and re-discovered the need for the StringVar. I edited my answer to use the StringVar and actually be correct, but I have to agree that using .config is simpler for this case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.