Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Checking Key press whilst tkinter loop is running

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To detect if a key is pressed you can use root.bind('<Key>', 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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading