Home > Enterprise >  how to detect keypress and keyrelease of keys like "shift","Enter","Capsloc
how to detect keypress and keyrelease of keys like "shift","Enter","Capsloc

Time:08-24

this works for normal keys like [q,w,e,r,1,2,3] but i cant make it work with keys like with Shift,Enter,Backspace etc,any idea how to make it work?

from tkinter import *
root=Tk()
root.geometry("200x200")
def func1(event):
    print(f'{event.char} key was pressed')
def func2(event):
    print(f'{event.char} key was released')
root.bind("<KeyPress>",func1)
root.bind("<KeyPress>",func2)
root.mainloop()

CodePudding user response:

From the docs:

.char: If the event was related to a KeyPress or KeyRelease for a key that produces a regular ASCII character, this string will be set to that character. (For special keys like delete, see the .keysym attribute, below.)

Since here you are trying to get a special key like Shift, Caps and so on, you can use keysym which will provide the key name.

Based on your comments, I see that you were expecting for a function that will trigger when the Shift key was pressed and released. This can be achieved by using KeyPress and KeyRelease before the key name:

def func1(event):
    print(f'{event.keysym} key was pressed')
def func2(event):
    print(f'{event.keysym} key was released')

root.bind("<KeyPress-Shift_L>",func1)
root.bind("<KeyRelease-Shift_L>",func2)

Some useful reference links:

CodePudding user response:

you have to use these to .bind function :

root.bind("<Alt-s>",fAlt) # Alt s pressed
root.bind("<Control-c>",func) # C character   Ctrl
root.bind("<Alt>",func1)  # The Alt key is held
root.bind("<Control>",func2)  # The Ctrl key is held
root.bind("<Shift>",func3)  # The Shift key is held
root.bind("<KeyPress>",func4)

root.bind('<Left>', leftKey)
root.bind('<Right>', rightKey)
root.bind('<Up>', upKey)
root.bind('<Down>', downKey)
  • Related