【发布时间】:2020-06-18 18:45:06
【问题描述】:
我正在尝试学习如何使用 TKinter 为 Python 应用程序制作 GUI。我正在尝试创建番茄钟计时器,但遇到了几个问题。
- 我在另一个函数中运行
while循环以在剩余时间内更新标签 - 在循环 GUI 无响应时(没关系)
- 我搜索了一下,查看了一些 StackOverflow 问题,发现这个函数运行循环可以在单独的线程中运行。
这解决了第一个问题,但还有另一个问题
- 取消按钮有效,但我没有看到点击动画。
- 定时器不会立即停止。
您能否解释一下为什么会发生这种情况以及我可以做些什么来提高我的 GUI 的响应能力?
import time
import tkinter
import winsound
from tkinter.ttk import Combobox
import threading
def run_thread():
global stop
stop = False
start_timer_btn.grab_release()
threading.Thread(target=countdown()).start()
def stop_timer():
global stop
stop = True
def countdown():
option = combo.get()
if option == "25":
seconds = 1500
elif option == "15":
seconds = 900
# elif option == "2":
# countdown(300)
# elif option == "3":
# countdown(1200)
global stop
while seconds and not stop:
seconds -= 1
print("minutes", seconds // 60, "seconds", seconds % 60)
timer_label.configure(text=str(seconds // 60) + ":" + str(seconds % 60))
window.update()
time.sleep(1)
winsound.PlaySound("SystemExit", winsound.SND_ALIAS)
stop = False
window = tkinter.Tk()
window.title("POMODORO Timer")
window.geometry("300x250")
combo = tkinter.ttk.Combobox(window)
combo["values"] = [25, 15]
combo.current(1)
timer_label = tkinter.Label(window, text="00:00")
start_timer_btn = tkinter.Button(window, text="Start timer", bg="green", fg="white", command=run_thread)
stop_timer_btn = tkinter.Button(window, text="Stop timer", bg="red", fg="white", command=stop_timer)
combo.grid(row=1, column=0)
start_timer_btn.grid(row=1, column=1)
stop_timer_btn.grid(row=1, column=2)
timer_label.grid(row=0, column=2, columnspan=3)
window.mainloop()
【问题讨论】: