Skip to main content
 首页 » 编程设计

python之如何在 python 中使用启动/停止 GUI 添加计时器

2024年11月01日29over140

我整天都在谷歌搜索,尝试了很多不同的方法,但我无法让这段代码工作。我想要一个简单的计时器,它在您按下“开始”时运行一个功能,并在您按下“停止”时停止。

例子: 当您按下开始时,该函数将每秒打印一次“Hello World”,直到您按下停止。

我的代码带有一些注释,以便您可以更快地理解:

import sys 
from Tkinter import * 
from threading import Timer 
# a boolean for telling the timer to stop 
stop_timer = False 
 
mgui = Tk() 
 
def work(var): 
    # stop_timers sets to True or False with Start/Stop 
    stop_timer = var 
    # work_done will evaluate if timer should start or be canceled 
    def work_done(var2): 
        stop_timer = var2 
        # if stop was pressed t.start() will be ignored 
        if stop_timer == False: 
            t.start() 
        # if stop was pressed timer will stop 
        if stop_timer == True: 
            print "Stopped!" 
            t.cancel() 
    t = Timer(1, work, [False]) 
    print "Something" 
    work_done(var) 
 
mgui.geometry('450x450') 
mgui.title('Test') 
 
cmd1 = lambda: work(False) 
btn = Button(mgui, text="Start", command =cmd1).place(x=50, y=50) 
cmd2 = lambda: work(True) 
btn2 = Button(mgui, text="Stop", command =cmd2).place(x=100, y=50) 
 
mgui.mainloop() 

如您所知,我是这个 shizzle 的新手! 谢谢,伙计们!

请您参考如下方法:

这是一个通用计时器,您也可以使用 after 在 tkinter 中实现一个:

import time 
import Tkinter as tk 
 
import threading 
 
class MyTimer(threading.Thread): 
 
    def __init__(self, t): 
        super(MyTimer,self).__init__() 
        self.txt = t 
        self.running = True 
 
    def run(self): 
        while self.running: 
            self.txt['text'] = time.time()         
 
 
mgui = tk.Tk() 
mgui.title('Test') 
 
txt = tk.Label(mgui, text="time") 
txt.grid(row=0,columnspan=2) 
 
timer = None 
def cmd1(): 
    global timer 
    timer = MyTimer(txt) 
    timer.start() 
def cmd2(): 
    global timer 
    if timer: 
        timer.running = False 
        timer= None 
 
btn = tk.Button(mgui, text="Start", command =cmd1) 
btn.grid(row=1,column=1) 
btn2 = tk.Button(mgui, text="Stop", command =cmd2) 
btn2.grid(row=1,column=2) 
 
mgui.mainloop()