嗯,伙计们,抱歉线程的标题。这有点令人困惑,但我认为理解我正在尝试用这个做什么会更容易
from Tkinter import *
from threading import Timer
class Application (Tk):
def __init__ (self, master = None):
Tk.__init__ (self, master)
self.createWidgets()
def createWidgets (self):
self.cuadro1 = Frame (self)
self.cuadro1.grid (row=0,column=0)
self.threadButton = Button (self.cuadro1)
self.threadButton.config (text = "Simular", state = NORMAL, command = self.startTimer)
self.threadButton.grid (row=0, column=0)
def startTimer (self):
self.threadButton.config (state = DISABLED)
self.proceso = Timer (5.0, self.printingStuff)
self.proceso.setDaemon (True)
self.proceso.start ()
#self.proceso.join ()
def cancellingTimer (self, Event):
if self.proceso.isAlive ():
print "Cancelling if Timer has started"
self.proceso.cancel ()
self.threadButton.config (state = NORMAL)
def printingStuff (self):
print "Hello World"
self.threadButton.config (state = NORMAL)
if __name__ == "__main__":
app = Application ()
app.resizable (height = False, width = False)
app.bind ("<KeyPress-q>", app.cancellingTimer)
app.mainloop ()
所以我有一个按钮,如果用户按下它,则调用startTimer方法并实例化Timer对象。如果用户在Timer的构造函数中指定的秒数之前按下“q”,将调用一个方法从打印“hello world”中取消它
编辑:所以这是按下按钮两次后的输出,第二次按“q”后取消定时器
"Hello World
Cancelling if Timer has started"
问题是我在startTimer方法中需要这样的东西:
def startTimer (self):
for x in range (0 ,10):
self.threadButton.config (state = DISABLED)
self.proceso = Timer (5.0, self.printingStuff)
self.proceso.setDaemon (True)
self.proceso.start ()
#self.proceso.join ()
一个循环将导致混乱,并且join方法将阻止我按“q”(至少在我的代码上)。你有任何sugestions或者你知道正确的方法吗?
编辑:这是输出按下按钮两次,包括句子循环。第二次之后我像上次一样按“q”
"Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Cancelling if Timer has started
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World"
10 Hello Hellos如预期,一个取消后跟9个Hello Worlds。我需要逐个执行它们而不阻塞事件处理程序,所以我可以逐个取消它们。
示例:
press button
*wait 5 seconds*
print "Hello World"
*pressing "q" after 1 second*
print "Cancelling timer"
*pressing "q" after 2 seconds*
print "Cancelling timer"
*wait 5 seconds*
print "Hello World"
.....
先谢谢你们