简体   繁体   中英

How to check if key has been pressed with Tkinter?

So I'm making a program where it detects if you have clicked a key on your keyboard. I know you can do:

def show(key):
    if key == Key.tab:
       print("Click")


with Listener(on_press=show) as listener:
    listener.join()

Except I want it to detect if a key has been pressed if the Tkinter window isn't open. Like if I keep the Tkinter window open, switch to Chrome, click Tab, I still want the program to print "Click"

Download the keyboard module: pip3 install keyboard

import keyboard #Using module keyboard
while True:#making a loop
try: #used try so that if user pressed other than the given key error will not be shown
    if keyboard.is_pressed('a'): #if key 'a' is pressed 
        print('You Pressed A Key!')
        break #finishing the loop
    else:
        pass
except:
    break #if user pressed other than the given key the loop will break

or use msvcrt module: import msvcrt

while True:
if msvcrt.kbhit():
    print('CLİCK')



import keyboard#Keyboard module in Python

rk = keyboard.record(until ='q')#It records all the keys until escape is pressed

keyboard.play(rk, speed_factor = 1)#It replay back the all keys

You can register a callback whenever a key is pressed using .on_press() from keyboard module.

Below is an example:

import tkinter as tk
import keyboard

def on_key(event):
    if event.name == "tab":
        key_label.config(text="Click")
        # clear the label after 100ms
        root.after(100, lambda: key_label.config(text=""))

root = tk.Tk()
key_label = tk.Label(root, width=10, font="Arial 24 bold")
key_label.pack(padx=100, pady=50)

keyboard.on_press(on_key)
root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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