基于Tkinter的最小化程序中的热键

问题描述 投票:2回答:2

我正在为某个游戏编程,我想在游戏以全屏模式运行时使用F7热键启动/停止脚本。我尝试使用root.bindpynput来执行此操作,但是它们都没有起作用。

这是我的代码:

hack_running = False


def hack():
    if  hack_running:
        PressKeyPynput(0x02)
        time.sleep(0.08)
        ReleaseKeyPynput(0x02)
        PressKeyPynput(0x11)
        time.sleep(0.5)
        ReleaseKeyPynput(0x11)
        PressKeyPynput(0x1F)
        time.sleep(0.6)
        ReleaseKeyPynput(0x1F)
        PressKeyPynput(0x02)
        time.sleep(0.08)
        ReleaseKeyPynput(0x02)
        root.after(900000, hack)

def Start_stop():
    global hack_running
    if Startk['text'] == 'Start':
        hack_running = True
        hack()
        Startk.config(text='Stop')
    else:
        hack_running = False
        Startk.config(text='Start')


root = tk.Tk()

root.resizable(False, False)

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

frame = tk.Frame(root, bg='black')
frame.place(relwidth=1, relheight=1)

Startk = tk.Button(frame, text='Start', font=("Calibri", 10), command=Start_stop)
Startk.pack(side='top', pady='50')

root.mainloop()
python python-3.x user-interface tkinter hotkeys
2个回答
2
投票

尝试使用Pynput:

import pynput

def run():
    print('f7') # your code

def press(key):
    if key == pynput.keyboard.Key.f7:
        run()

pynput.keyboard.Listener(on_press=press).run()

关于键盘组合,请参见this github issue。希望对您有所帮助!


2
投票

Pynput具有一个简单的类,提供了称为GlobalHotKeys的热键功能。Reference here.


不幸的是,如果只有python,如果您想使其在游戏中运行,我认为它不能做更多的事情。

[通常,游戏中还有键盘侦听器线程。当您的python脚本与您的游戏一起使用时,会引起冲突。并且您的python脚本无法正常工作。(并且游戏将始终采取一些措施来防止作弊。 )

据我所知,AutoHotkey脚本可以在游戏中工作(至少过去对我有用)。AutoHotkey Official document。在macOSrefer this

© www.soinside.com 2019 - 2024. All rights reserved.