简体   繁体   English

如何使用 tkinter/python 检测键盘/鼠标上按下了哪个键?

[英]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.我正在使用 tkinter 制作一个 python 应用程序,我需要让用户选择他们将使用哪个键来执行某些特定操作。 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?如何让用户按下按键?

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

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).要扩展@darthmorf 的答案以便还检测鼠标按钮事件,您需要为鼠标按钮添加单独的事件绑定,该事件绑定将在任何鼠标按钮按下时触发,或'<Button>' '<Button-1>' ,(或 2 或 3)将在按下该特定按钮时触发(其中 '1' 是鼠标左键,'2' 是右键,'3' 是中间...虽然我想想在 Mac 上,右边和中间的按钮是交换的)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM