3

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?

2 Answers 2

4

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()
Sign up to request clarification or add additional context in comments.

2 Comments

I was testing it and I didn't found a way no make it also recognize the mouse keys. Do you know anything about it?
See below for mouse stuff!
3

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

1 Comment

I updated my answer to handle both key and button events in a single function. It's cleaner this way!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.