Python練習題(五)


在這裏插入圖片描述

tkinter多線程計時器

import tkinter as tk
from threading import Thread, Event

hour = 0


class ControlThread(Thread):
    def __init__(self):
        self._stop_event = Event()
        Thread.__init__(self)

    def run(self):
        f1()

    def terminate(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()


def f1():  # 計時
    def count():
        global hour
        global x
        hour += 1
        hour %= 24
        label_hour.config(text=str(hour))
        x = label_hour.after(3600, count)
    count()


def run():
    global t1
    t1 = ControlThread()
    t1.start()


def stop():
    global t1
    label_hour.after_cancel(x)
    t1.terminate()


root = tk.Tk()

root.title("time")

label_hour = tk.Label(root, bg="lightblue", height=2, width=10)
label_hour.grid(row=0, column=0, columnspan=3)

button_run = tk.Button(root, text="Run", command=run)
button_run.grid(row=1, column=0)

button_stop = tk.Button(root, text="Stop", command=stop)
button_stop.grid(row=1, column=2)

root.mainloop()

未完待續,,,

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章