Python Tkinter - 在tkinter中使用time.clock
我想创建一个tkinter的功能,让一些变量跟时间有关。我希望每隔一段时间,顾客的变量就会更新一次。在这个例子中,我想模拟每5秒就会有顾客进店的情况。不过,当我点击顾客菜单的时候,它并没有更新。请问我该怎么让它更新呢?而time.clock()这个函数是会更新的。
import time
from Tkinter import *
import tkMessageBox
mGui = Tk()
mGui.title("Experiment")
mGui.geometry('450x450+500+300')
def customers():
tkMessageBox.showinfo(title="Customers", message=people)
def timer():
tkMessageBox.showinfo(title="Customers", message=time.clock())
people = time.clock()/5
label1 = Label(mGui, text = "label 1").pack()
##Menu
menubar = Menu(mGui)
filemenu = Menu(menubar, tearoff = 0)
menubar.add_cascade(label="In Line", menu=filemenu)
filemenu.add_command(label="Customers", command = customers)
filemenu.add_command(label="Time", command = timer)
mGui.config(menu=menubar)
mGui.mainloop()
1 个回答
2
简单来说,你只调用了一次这个函数。你的变量 people
只在 time.clock()
被调用时设置了一次——它不会像你想的那样自动更新,所以当你调用 customers
时,它显示的还是之前的那个值。
一个简单的解决办法是:
def customers():
people = time.clock()//5 # // is integer division. Equivalent to math.floor(x/y)
tkMessageBox.showinfo(title="Customers", message=people)
def timer():
tkMessageBox.showinfo(title="Timer", message=time.clock()
不过,这可能不是最好的实现方式,因为你需要点击一个按钮才能看到每次的更新。那不如把它们设置为 StringVar
呢?
mGui = Tk() # set geometry as needed
people = StringVar(master=mGui, value='')
timer = StringVar(master=mGui, value=time.clock())
def update_customers():
global mGui
people.set(time.clock()//5)
mGui.after(1000, update_customers)
# this sets the function to run again after ~1s and re-evaluate
def update_timer():
global mGui
timer.set(5 - (time.clock() % 5))
mGui.after(1000, update_timer)
# this sets the function to run again after ~1s and re-evaluate
def start():
global mGui, people, timer
update_customers()
update_timer()
Label(mGui, text="Customers:").pack()
Label(mGui, textvariable=people).pack()
Label(mGui, text="Time 'till Next Customer:").pack()
Label(mGui, textvariable=timer).pack()
mGui.mainloop()
start()