用 Python 和 Tkinter 制作倒数计时器? [英] Making a countdown timer with Python and Tkinter?

查看:55
本文介绍了用 Python 和 Tkinter 制作倒数计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用倒数计时器功能在 Tkinter 中设置标签.现在它所做的就是在达到 10 时将标签设置为10",我真的不明白为什么.此外,即使我将计时器打印到终端而不是时间到了!"位从不打印.

I want to set a label in Tkinter using my countdown timer function. Right now all it does is set the lable to "10" once 10 is reached and I don't really understand why. Also, even if I have the timer print to a terminal instead the "Time's up!" bit never prints.

import time
import tkinter as tk

class App():
    def __init__(self):
        self.root = tk.Tk()
        self.label = tk.Label(text="null")
        self.label.pack()
        self.countdown()
        self.root.mainloop()

    # Define a timer.
    def countdown(self):
        p = 10.00
        t = time.time()
        n = 0
        # Loop while the number of seconds is less than the integer defined in "p"
        while n - t < p: 
            n = time.time()
            if n == t + p:
                self.label.configure(text="Time's up!")
            else:
                self.label.configure(text=round(n - t))

app=App()

推荐答案

Tkinter 已经有一个无限循环运行(事件循环),以及一种在一段时间过去后安排事情运行的方法(使用 之后).您可以通过编写一个每秒调用一次自身来更新显示的函数来利用这一点.您可以使用类变量来跟踪剩余时间.

Tkinter already has an infinite loop running (the event loop), and a way to schedule things to run after a period of time has elapsed (using after). You can take advantage of this by writing a function that calls itself once a second to update the display. You can use a class variable to keep track of the remaining time.

import Tkinter as tk

class ExampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.label = tk.Label(self, text="", width=10)
        self.label.pack()
        self.remaining = 0
        self.countdown(10)

    def countdown(self, remaining = None):
        if remaining is not None:
            self.remaining = remaining

        if self.remaining <= 0:
            self.label.configure(text="time's up!")
        else:
            self.label.configure(text="%d" % self.remaining)
            self.remaining = self.remaining - 1
            self.after(1000, self.countdown)

if __name__ == "__main__":
    app = ExampleApp()
    app.mainloop()

这篇关于用 Python 和 Tkinter 制作倒数计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆