计时器或秒表在python中

时间:2014-12-18 16:55:35

标签: python time

我正在尝试创建一个测验(基于GUI)。我想在我的代码中插入一个计时器,即测验只有30秒,之后程序终止一条消息。我怎样才能做到这一点?我正在使用Tkinter。 我使用的是python 2.7版本。

1 个答案:

答案 0 :(得分:2)

启动计时器
a_timer=root.after(some_ms_seconds,some_method)

将在时间结束后调用some_method()

例如,如果你想做一个倒数计时器

foo = StringVar()
foo.set(30)
a_time_label = Label(root,textvariable=foo)
def decrement_label():
    foo.set(str(int(foo.get())-1))
root.after(1000,decrement_label)

然后你可以用

来阻止它
root.cancel_after(a_timer) #cancel the timers call back

如果您需要更多帮助,则必须更新您的问题

因为我在这里感觉特别慷慨

from Tkinter import Tk, Button,Label,StringVar,LEFT,RIGHT,BOTTOM,TOP
import tkMessageBox
import random
class MyButton:
    def __init__(self,root,label,**config):
        self.text_var = StringVar()
        self.text_var.set(label)
        self.btn = Button(root,textvariable=self.text_var,**config)
    def SetLabel(self,label,**config):
        self.text_var.set(label)
        self.btn.configure(**config)
    def GetLabel(self):
        return self.text_var.get()
    def __getattr__(self,attr):
        return getattr(self.btn,attr)
class MyQuiz:
    def check_button(self,btn):
        if btn.cget("bg") == "green":
            tkMessageBox.showinfo("WINNER!!!","You picked the right one!")
            return True
        else:
            tkMessageBox.showinfo("Sorry no Luck","You picked the WRONG one!")

    def on_button(self,button_index):
        self.root.after_cancel(self.timer)
        if self.check_button(self.buttons[button_index]):
            self.buttons[button_index].configure(bg="red")
            self.buttons[random.randint(0,2)].configure(bg="green")
            self.timer_text.set("30")
        self.timer = self.root.after(1000,self.on_timer)

    def on_timer(self):
        time_left = int(self.timer_text.get()) - 1
        if time_left <= 0:
            tkMessageBox.showinfo("Out of Time!","You Ran Out Of Time!!!")
        else:
            self.timer_text.set(str(time_left))
            self.timer = self.root.after(1000,self.on_timer)    
    def __init__(self):
        self.root = root = Tk()
        self.timer_text=StringVar()
        self.timer_text.set("30")
        self.label1 = Label(self.root,text="Pick The Right One")
        self.label2 = Label(self.root,textvariable=self.timer_text)
        self.label1.pack(side=TOP)
        self.label2.pack(side=RIGHT)
        self.buttons = [MyButton(root,"Button1",bg="green",command=lambda:self.on_button(0)),
                        MyButton(root,"Button2",bg="red",command=lambda:self.on_button(1)),
                        MyButton(root,"Button3",bg="red",command=lambda:self.on_button(2)),]
        self.buttons[0].pack(side=TOP)
        self.buttons[1].pack(side=TOP)
        self.buttons[2].pack(side=TOP)
        self.timer = root.after(1000,self.on_timer)
        self.root.mainloop()

MyQuiz()
相关问题