我正在尝试通过单击按钮更新Python中标签的内容。对于每次单击,将引发计数器,并且标签的值将由计数器(j)的当前值更新。这是代码:
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()
请善待,我是Python新手。 :)
答案 0 :(得分:3)
您可以使用Tkinter variable class实例来保存值。如果将textvariable
窗口小部件的Label
选项分配给变量类实例,它将在实例值更改时自动更新。这是一个例子:
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()
答案 1 :(得分:1)
您可以使用PrintNumber()
更改响应命令(在本例中为label.config()
)的函数中的标签文本,例如:
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()
答案 2 :(得分:0)
这是你可以做到的另一种方式
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()