How do I check if a key has been pressed in TKinter outside the window?

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

However, I want it to detect a keypress even when the root window isn't selected. For example, let's say I switch my window to Google Chrome. Although the Tkinter window is selected, I want to detect if you were to press 'tab.'


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

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