sbb
sbb

Reputation: 176

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?

Upvotes: 3

Views: 956

Answers (2)

JRiggles
JRiggles

Reputation: 6810

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

Upvotes: 3

darthmorf
darthmorf

Reputation: 158

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

Upvotes: 4

Related Questions