Reputation: 69
I'm trying to update the content of a label, in Python, by clicking a button. For each clicks a counter will be raised and the value of the label will be updated by the current value of the counter (j). Here is the code:
import time
import random
import MySQLdb
from Tkinter import *
j=0
def PrintNumber():
global j
j+=1
print j
return
mgui=Tk()
mgui.geometry('200x200')
mgui.title('Queue System')
st = Button(mgui, text="Next Customer", command = PrintNumber)
st.pack()
f = PrintNumber()
label = Label(mgui, text=f)
label.pack()
mgui.mainloop()
Please be kind, i'm new in Python. :)
Upvotes: 2
Views: 3189
Reputation: 102
Here is another way you could do it
import time
import random
import MySQLdb
from Tkinter import *
def PrintNumber(label):
PrintNumber.counter += 1 #simulates a static variable
print PrintNumber.counter
label.configure(text=str(PrintNumber.counter)) #you update label here
mgui=Tk()
mgui.geometry('200x200')
mgui.title('Queue System')
PrintNumber.counter = 0 #add an attribute to a function and use it as a static variable
label = Label(mgui) #create label
#pass the label as parameter to your function using lambda notation
st = Button(mgui, text="Next Customer", command=lambda label=label:PrintNumber(label))
st.pack()
label.pack()
mgui.mainloop()
Upvotes: 0
Reputation: 3964
You can use a Tkinter variable class instance to hold a value. If you assign the textvariable
option of the Label
widget to the variable class instance, it will update automatically as the value of the instance changes. Here's an example:
from Tkinter import *
root = Tk()
var = IntVar() # instantiate the IntVar variable class
var.set(0) # set it to 0 as the initial value
# the button command is a lambda expression that calls the set method on the var,
# with the var value (var.get) increased by 1 as the argument
Button(root, text="Next Customer", command=lambda: var.set(var.get() + 1)).pack()
# the label's textvariable is set to the variable class instance
Label(root, textvariable=var).pack()
mainloop()
Upvotes: 3
Reputation: 10841
You can change the label text in the function that responds to the command (PrintNumber()
in this case) using label.config()
, e.g.:
from tkinter import *
def PrintNumber():
global j,label
j+=1
label.config(text=str(j))
return
j = 0
mgui=Tk()
mgui.geometry('200x200')
mgui.title('Queue System')
st = Button(mgui, text="Next Customer", command = PrintNumber)
st.pack()
label = Label(mgui, text=str(j))
label.pack()
mgui.mainloop()
Upvotes: 1