0

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.'

Shlok Sharma
  • 130
  • 2
  • 9

2 Answers2

2

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()
acw1668
  • 40,144
  • 5
  • 22
  • 34
  • In this case the `keyboard` module will start a new thread to call your `on_key` function. And you shouldn't call any `tkinter` functions from threads other than the one where you created the `tk.Tk()`. – TheLizzard Aug 17 '21 at 10:21
1

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
Django
  • 160
  • 2
  • 13
  • But since its a while loop the Tkinter window won't open until I press 'a'. I want to find a way I can open the Tkinter window, switch to a different window, press 'a' and it should still print. Sorry if I'm phrasing this wrong. – Shlok Sharma May 16 '21 at 17:27
  • As long as the program is open and the q key is not pressed, it will give the key that was pressed. – Django May 16 '21 at 17:40
  • Tutorial for keyboard module: https://www.youtube.com/watch?v=GLnNPjL1U2g&t=430s – Django May 16 '21 at 17:47
  • You actually could put this in a loop using `after()` that way it can run always and not interfere with `mainloop()` or maybe use `threading` – Matiiss May 16 '21 at 18:56
  • did You test this with tkinter? – Matiiss May 16 '21 at 19:01