Python Tkinter - 使用tkinter的time.clock

时间:2014-07-15 04:31:20

标签: python tkinter

我想创建一个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 个答案:

答案 0 :(得分: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()
相关问题