如果没有来自Thread类的join方法,如何在不阻塞事件处理程序的情况下阻塞调用线程?Python蒂姆

2024-09-27 21:33:04 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,伙计们,为这条线的标题感到抱歉。这有点让人困惑,但我想更容易理解我想用这个做什么

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对象。如果用户在计时器的构造函数中指定的秒数之前按“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”(至少在我的代码上)。你有什么建议或者知道正确的方法吗?你知道吗

编辑:这里的输出按下按钮两次,包括句子循环。第二次之后,我像上次一样按“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 worlds,一个取消,然后是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"
.....

提前谢谢伙计们


Tags: 方法selfconfigapphelloworldifdef

热门问题