1 回答
TA貢獻1725條經驗 獲得超8個贊
在您的代碼中,tkinter 循環阻塞了主循環。當計時器完成時,您需要退出 tk 循環。您還需要僅在啟動計時器時才啟動 tk 循環,否則 tk 循環將永遠不會退出。
這是工作代碼:
import tkinter as tkr
import keyboard
from playsound import playsound
root = None
timer_display = None
root = tkr.Tk()
root.geometry("+0+0")
root.overrideredirect(True)
root.wm_attributes("-topmost", True)
root.wm_attributes("-alpha", 0.01)
root.resizable(0, 0)
timer_display = tkr.Label(root, font=('Trebuchet MS', 30, 'bold'), bg='black')
timer_display.pack()
seconds = 45
toggle_button = 'x'
enabled = False
def countdown(time):
if time > 0:
mins, secs = divmod(time, 60)
def color_change(t_time):
if t_time > 10:
return 'green'
elif 7 <= t_time <= 10:
return 'yellow'
elif t_time < 7:
return 'red'
timer_display.config(text="{:02d}:{:02d}".format(mins, secs),
fg=color_change(time)), root.after(1000, countdown, time - 1)
else:
root.wm_attributes('-alpha', 0.01)
root.quit() # exit tk root loop
def start_countdown():
root.wm_attributes('-alpha', 0.7)
countdown(seconds)
last_state = False
while True:
key_down = keyboard.is_pressed(toggle_button)
# If the toggle button is pressed, toggle the enabled value and print
if key_down != last_state:
last_state = key_down
if last_state:
enabled = True
if enabled:
start_countdown()
print("Activated")
playsound('count.mp3')
else:
start_countdown()
root.mainloop() # timer will exit this loop
添加回答
舉報
