我想将全局热键(使用 pynput 模块)添加到我的 Tkinter 脚本(随机数生成器)中。每次按“f7”按钮时,我都想获得随机数。它还必须在不专注于应用程序的情况下工作。不幸的是,该应用程序在一段时间后没有响应。它工作了一次/两次,但大约一分钟后它就被冻结了。
import tkinter as tk
import random
from pynput import keyboard
rng = random.SystemRandom()
def Draw():
global text
frame=tk.Frame(root,width=100,height=100,relief='solid',bd=0)
frame.place(relx = 0.5, rely = 0.5, anchor = 'center')
text=tk.Label(frame,text='HELLO', font = "Helvetica 65 bold", justify='center')
text.pack()
def on_press(key):
try:
k = key.char
except:
k = key.name
if k in ['f7']:
return False #stop listening
n = 0
def Refresher():
global text
global n
text.configure(text=rng.randint(0,100), fg ="white", bg = "black")
root.after(100, Refresher)
if n == 1:
listener = keyboard.Listener(on_press=on_press)
listener.start()
listener.join()
n = 1
root=tk.Tk()
root["bg"] = "black"
root.title("RNG")
Draw()
Refresher()
root.mainloop()