简体   繁体   English

使用 Tkinter 捕获系统的所有按键

[英]Capture all keypresses of the system with Tkinter

I'm coding a little tool that displays the key presses on the screen with Tkinter, useful for screen recording.我正在编写一个小工具,用 Tkinter 在屏幕上显示按键,对屏幕录制很有用。

Is there a way to get a listener for all key presses of the system globally with Tkinter?有没有办法通过 Tkinter 获取全局系统所有按键的监听器? (for every keystroke including F1 , CTRL , ..., even when the Tkinter window does not have the focus) (对于包括F1CTRL ,...在内的每次击键,即使 Tkinter window 没有焦点)

I currently know a solution with pyHook.HookManager() , pythoncom.PumpMessages() , and also solutions from Listen for a shortcut (like WIN+A) even if the Python script does not have the focus but is there a 100% tkinter solution?我目前知道pyHook.HookManager()pythoncom.PumpMessages()的解决方案,以及Listen for a shortcut (like WIN+A) 的解决方案,即使 Python 脚本没有焦点,但是否有 100% tkinter解决方案?

Indeed, pyhook is only for Python 2, and pyhook3 seems to be abandoned, so I would prefer a built-in Python3 / Tkinter solution for Windows.确实, pyhook只针对Python 2, pyhook3好像被抛弃了,所以我更喜欢Windows内置的Python3 / Tkinter解决方案

Solution 1 : if you need to catch keyboard events in your current window, you can use:解决方案1 :如果你需要在你当前的window中捕捉键盘事件,你可以使用:

from tkinter import *
 
def key_press(event):
    key = event.char
    print(f"'{key}' is pressed")
 
root = Tk()
root.geometry('640x480')
root.bind('<Key>', key_press)
mainloop()

Solution 2 : if you want to capture keys regardless of which window has focus, you can use keyboard解决方案2 :如果你想捕获按键而不管哪个window有焦点,你可以使用keyboard

As suggested in tkinter using two keys at the same time , you can detect all key pressed at the same time with the following:正如tkinter 同时使用两个键所建议的那样,您可以使用以下方法检测同时按下的所有键:


history = []
def keyup(e):
    print(e.keycode)
    if  e.keycode in history :
        history.pop(history.index(e.keycode))

        var.set(str(history))

def keydown(e):
    if not e.keycode in history :
        history.append(e.keycode)
        var.set(str(history))

root = Tk()
root.bind("<KeyPress>", keydown)
root.bind("<KeyRelease>", keyup)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM