我整天都在疯狂地尝试各种各样的方式,但是我无法使用这些代码。我想要一个简单的计时器,当你按“开始”时运行一个功能,当你按“停止”时停止。
实施例: 当您按开始时,该功能将每秒打印一次“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的新手! 谢谢,伙伴们!
答案 0 :(得分:1)
这是一个通用计时器,你也可以使用after
在
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()
答案 1 :(得分:0)
通过在xndrme的帖子中编辑一些内容,我终于开始工作了。谢谢!
我会在这里发布可能的未来google的代码。
import sys
from Tkinter import *
from threading import Timer
mgui = Tk()
def cmd2():
global t
if t:
t.cancel()
def looper():
global t
t = Timer(1, looper)
t.start()
print "Hello World!"
mgui.geometry('450x450')
mgui.title('Test')
btn = Button(mgui, text="Start", command =looper).place(x=50, y=50)
btn2 = Button(mgui, text="Stop", command =cmd2).place(x=100, y=50)
mgui.mainloop()