Home > Back-end >  How to detect which key was pressed on keyboard/mouse using tkinter/python?
How to detect which key was pressed on keyboard/mouse using tkinter/python?

Time:06-21

I'm using tkinter to make a python app and I need to let the user choose which key they will use to do some specific action. Then I want to make a button which when the user clicks it, the next key they press as well in keyboard as in mouse will be detected and then it will be bound it to that specific action. How can I get the key pressed by the user?

CodePudding user response:

You can get key presses pretty easily. Without knowing your code, it's hard to say exactly what you will need, but the below code will display a label with the last key pressed when ran and should provide enough of an example to show you how to adapt it to your program!

from tkinter import Tk, Label

root=Tk()

def key_pressed(event):
    w=Label(root,text="Key Pressed: " event.char)
    w.place(x=70,y=90)

root.bind("<Key>",key_pressed)
root.mainloop()
  • Related