python - 切换不工作的“键盘”Python 和 Tkinter
问题描述
你好,我的开关不工作,
工作代码:当我按下 xa 45 秒计时器启动。45 秒后,计时器消失,然后当我再次按 x 时,没有任何反应。
我想要实现的目标:45 秒后,我想再次单击 x 以再次启动计时器并继续执行此操作:
from tkinter import *
import keyboard
from playsound import playsound
root = Tk()
root.geometry("+0+0")
root.overrideredirect(True)
root.wm_attributes("-topmost", True)
root.wm_attributes("-alpha", 0.01)
root.resizable(0, 0)
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)
def start_countdown():
root.wm_attributes('-alpha', 0.7)
countdown(seconds)
timer_display = Label(root, font=('Trebuchet MS', 30, 'bold'), bg='black')
timer_display.pack()
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()
解决方案
在您的代码中,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
推荐阅读
- javascript - 将 firebase 身份验证与 Next.js 集成
- python - Jupyter 日期函数
- python - 循环遍历 Python 中的列表项
- python - 访问 solve_ivp 中的当前步长并将其转发到要集成的函数
- macos - SwiftUI 列表未更新
- javascript - 反应useEffect异步警告?
- javascript - 单击时如何获取按钮的事件目标而不是按钮内部的内容
- r - R中的多元线性回归模型
- c - 如何获取任意类型的可变数量的参数并将每个参数打印在 C 中的单独行上?
- javascript - 混合 Typescript/Javascript 构建寻找永远不存在的文件