【问题标题】:Why doesn't after() wait [duplicate]为什么 after() 不等待[重复]
【发布时间】:2018-05-10 23:36:26
【问题描述】:

我是 Python 新手,想为训练目的构建一个睡眠定时器。 我在 Ubuntu 上使用 Python 3.6.3。 我想要一个标签,显示距离计算机进入睡眠状态还剩多少时间。

我正在使用after(),但每次我调用更新方法时,它都会经常调用自身,直到我通过 错误达到最大递归深度:

RecursionError: 调用 Python 对象时超出最大递归深度

我认为,出于某种原因,after(1000, self.update) 命令在再次调用该方法之前不会等待 1 秒。另外我不想要递归,而是每秒调用该方法...

你能告诉我我做错了什么吗?

class Application(Frame):

    def startTimer(self):
        self.start = time.time()
        self.waiting = self.entry.get()*60000
        self.update()
        self.after(self.waiting, self.shutdown)

    def update(self):
        string = str(int(int(self.waiting/6000) + self.start - time.time())/10)
        print(string)
        self.label.config(text = string + " Minuts left")
        self.after(1000, self.update())

    def shutdown(self):
        print("PSSST!")

    def createWidgets(self):
        self.entry = Scale(self, from_=5, to=120, orient=HORIZONTAL, resolution=5)
        self.label = Label(self,text="time remaining")

        self.start = Button(self, text="Start", fg="black",
                            command=self.startTimer)

        self.quit = Button(self, text="QUIT", fg="red",
                              command=root.quit)

        self.entry.pack(side="top")
        self.label.pack(side="left")
        self.start.pack(side="right")
        self.quit.pack(side="bottom")

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

root = Tk()
app = Application(master=root)
app.mainloop()`

【问题讨论】:

    标签: python-3.x tkinter timer


    【解决方案1】:

    在这一行:

    self.after(1000, self.update())
    

    您没有将self.update 函数传递给self.after,而是立即调用self.update() 并将结果传递给self.after。这会导致无限递归。

    【讨论】:

    • 嗯,谢谢...它适用于'self.after(1000,self.update)'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 2022-01-21
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多