Tkinter 中的全局热键

Global hotkey in Tkinter

我想将全局热键(使用 pynput 模块)添加到我的 Tkinter 脚本(随机数生成器)中。每次按 'f7' 按钮时,我都想获得随机数。它还必须在不关注应用程序的情况下工作。不幸的是,该应用程序在一段时间后没有响应。它工作 once/twice 但大约一分钟后它被冻结了。

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()

我找到了解决方案。我们需要 bindglobal 库,然后我们在 Tkinter 中有全局热键。更多信息:https://libraries.io/pypi/bindglobal

我的代码:

import tkinter as tk
import random
from bindglobal import BindGlobal

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.configure(text=rng.randint(0,100), fg ="white", bg = "black")
    text.pack()


def Refresher(e):
    global text
    text.configure(text=rng.randint(0,100), fg ="white", bg = "black")


root = tk.Tk()

root.title("RNG - F7")
root["bg"] = "black"

Draw()

bg = BindGlobal()
bg.start()
bg.gbind("<f7>",Refresher)

root.mainloop()

另外我需要修改提到的库,因为不支持 'F7' 按钮。

找到并打开 bindglobal/init.py 并添加 'f7',例如像这样:

class TkKeys(object):
    tk_keys = {}
    for i in ( 'space','BackSpace', 'Tab'
        , 'Delete', 'End', 'Home', 'Caps_Lock'
        ,'Left','Right', 'Up', 'Down', 'f7'
        ,'Menu','Insert', 'Pause', 'Num_Lock', 'Scroll_Lock' #Those fails on OSX
        ):