以下是一个无限制次数的自动计数器程序的设计,使用 tkinter 库来创建 GUI 界面:

import tkinter as tk

class CounterApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.counter = 0
        self.timer_running = False

        self.label = tk.Label(self, text='0', font=('Arial', 24))
        self.label.pack()

        self.start_button = tk.Button(self, text='Start', command=self.start_timer)
        self.start_button.pack()

        self.stop_button = tk.Button(self, text='Stop', command=self.stop_timer)
        self.stop_button.pack()

        self.timer = tk.Timer(1, self.update_counter)  # 每隔1秒更新计数器

    def start_timer(self):
        if not self.timer_running:
            self.timer.start()
            self.timer_running = True

    def stop_timer(self):
        if self.timer_running:
            self.timer.cancel()
            self.timer_running = False

    def update_counter(self):
        self.counter += 1
        self.label.config(text=str(self.counter))
        self.start_timer()  # 继续计时

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

这个程序使用了 tkinter 库来创建 GUI 界面。在窗口中,有一个 Label 标签用于显示计数器的值,以及一个 Start 按钮和一个 Stop 按钮用于启动和停止计时器。计数器的值通过一个变量 counter 来保存,并且在计时器每次触发时更新。计时器使用 Timer 类从 threading 库创建,并且设置为每隔1秒触发一次。启动计时器时,会调用 timer.start() 方法开始计时,并将 timer_running 标志设置为 True。停止计时器时,会调用 timer.cancel() 方法停止计时,并将 timer_running 标志设置为 False。在计时器触发时,会更新计数器的值,并调用 start_timer() 方法继续计时。


原文地址: https://www.cveoy.top/t/topic/o0wy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录