我正在编写一个计时器应用程序,它遇到了很多困难,但是其中一个已经在制作一个可以通过按下按钮来打破的循环。我已经研究过了,我的研究表明我应该使用线程,但我无法弄清楚它是如何工作的。
我决定尝试的是在调用键盘中断时发出异常,然后创建一个调用相同中断的按钮。但是,当我按ctrl-c时,我当前的代码拒绝中断。
我的示例代码如下所示
from Tkinter import *
from sys import exit
class Timer:
def __init__(self, master):
buttonstart = Button(master, text = "Start", fg = "blue", command = self.start)
buttonstart.grid(row = 1, column = 0)
buttonquit = Button(master, text = "Quit", fg = "blue", command= quit)
buttonquit.grid(row = 1, column = 2)
global timertext
timertext = DoubleVar()
timertext.set(0)
display = Label(master, textvariable = timertext)
display.grid(row = 0, column = 0)
timertext.set(timertext)
def timerlogic(self):
pass
def pause(self):
pass
def start(self):
global timertext
try:
while True:
#do things
except KeyboardInterrupt:
print "Interrupted"
def lap(self):
pass
root = Tk()
app = Timer(root)
root.mainloop()
root.destroy()
基本上,我不认为我的代码是可行的,但我不知道如何编辑它以创建一个我可以根据需要中断的循环。
答案 0 :(得分:3)
您将某个变量设置为True或False。此外,while循环会中断Tkinter循环,因此在while循环退出之前,Tkinter将不执行任何操作。改为使用功能后的Tkinter。
from Tkinter import *
##from sys import exit
class Timer:
def __init__(self, master):
self.master=master
buttonstart = Button(master, text = "Start", fg = "blue", command = self.start)
buttonstart.grid(row = 1, column = 0)
buttonquit = Button(master, text = "Quit", fg = "blue", command=self.quitit)
buttonquit.grid(row = 1, column = 2)
self.timertext = DoubleVar()
self.timertext.set(0)
display = Label(master, textvariable = self.timertext)
display.grid(row = 0, column = 0)
## timertext.set(timertext) ## Huh!!
self.timeit=False
def increment_timer(self):
ctr=int(self.timertext.get())
self.timertext.set(ctr+1)
if self.timeit:
self.master.after(500, self.increment_timer)
def start(self):
self.timeit=True
self.increment_timer()
def quitit(self):
self.timeit=False
root = Tk()
app = Timer(root)
root.mainloop()