I'm trying to check if the key "q" is pressed whilst running a tkinter loop. Is there a way to do this?
from tkinter import *
import keyboard
def DetectKeyPress():
if keyboard.read_key() == "p":
print("you pressed p!")
root = Tk()
DetectKeyPress()
root.mainloop()
CodePudding user response:
Focused tkinter window
To detect if a key is pressed you can useroot.bind('', function).
Please be aware that pressing shift and some other keys do count as an independent event.
from tkinter import *
def detect_key_press(event):
if event.char == "p":
print("you pressed p!")
root = Tk()
root.bind('<Key>', detect_key_press)
root.mainloop()
Not focused
To detect if a key is pressed while the window is not focused, you have to use keyboard (pip3 install keyboard). On Linux, this requires sudo privileges.
import keyboard
keyboard.add_hotkey('p', print, args=('you pressed p!',))
keyboard.wait('esc')
From https://www.geeksforgeeks.org/how-to-create-a-hotkey-in-python/
