使用消息框在循环之后打破Python

时间:2015-03-31 13:39:50

标签: python time tkinter messagebox

我是Python的新手。我有这个代码,并试图找到一种方法让消息框突破后循环。有没有办法用我的代码做到这一点,还是我必须以某种方式重写它?

from tkinter import *
import random
from tkinter import messagebox

class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def drawBox(self, canvas):
        color = hex(random.randrange(4095))[2:6]
        l = len(color)
        if l == 1:
            color = '00' + color
        elif l == 2:
            color = '0' + color
        color = '#' + color
        canvas.create_rectangle(100,100,200,200,fill=color)
        canvas.pack()

    def updateTimer(self, canvas, flag, timer):
        timer = self.after(100, lambda: self.drawBox(canvas))
        if flag == True:
            print('OK clicked')
            self.after_cancel(timer)
            return
        else:
            flag = False
            self.after(100, lambda: self.updateTimer(canvas, flag, timer))

    def initUI(self):
        self.parent.title('after_cancel test')
        self.pack(fill=BOTH, expand=1)
        canvas = Canvas(self)
        self.flag = False
        timer = self.after(100, lambda: self.updateTimer(canvas, self.flag, timer))
        if messagebox.askokcancel('Turn that thing off','Click OK to stop'):
            self.updateTimer(canvas, True, timer)

def main():
    root = Tk() 
    root.geometry("300x250+300+300")
    app = Example(root)
    root.mainloop()  

if __name__ == '__main__':
    main()

谢谢!

1 个答案:

答案 0 :(得分:2)

您已取消对after的{​​{1}}来电,但由于您仍然让self.drawBox(...)运行,因此循环继续。您应该使用

取消对self.updateTimer的下一次通话
self.updateTimer

self.after_id = self.after(100, lambda: self.updateTimer(canvas, flag, timer))

实际上,你这样做的方式比现在更难。您不需要self.after_cancel(self.after_id) 功能,并且您无需传递这么多变量,只需将它们设为updateTimer的属性即可。您还在每个循环中创建一个新的Canvas和一个新的矩形。这不是必需的,只需更改矩形的颜色即可。

简化代码:

self