Skip to content
Advertisement

How to detect which key was pressed on keyboard/mouse using tkinter/python?

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?

Advertisement

Answer

To expand on @darthmorf’s answer in order to also detect mouse button events, you’ll need to add a separate event binding for mouse buttons with either the '<Button>' event which will fire on any mouse button press, or '<Button-1>', (or 2 or 3) which will fire when that specific button is pressed (where ‘1’ is the left mouse button, ‘2’ is the right, and ‘3’ is the middle…though I think on Mac the right and middle buttons are swapped).

import tkinter as tk

root = tk.Tk()


def on_event(event):
    text = event.char if event.num == '??' else event.num
    label = tk.Label(root, text=text)
    label.place(x=50, y=50)


root.bind('<Key>', on_event)
root.bind('<Button>', on_event)
root.mainloop()
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement