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

发布于 2025-02-09 04:30:29 字数 131 浏览 2 评论 0原文

我正在使用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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北座城市 2025-02-16 04:30:29

您可以轻松地获得钥匙按钮。在不知道您的代码的情况下,很难确切地说出您需要的内容,但是以下代码将显示一个标签,并在运行时按下最后一个键,并且应该提供足够的示例,以向您展示如何使其适应您的程序!

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

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()
薔薇婲 2025-02-16 04:30:29

要在 @darthmorf的答案上展开以检测鼠标按钮事件,您需要使用'&lt; button&gt;'事件添加一个单独的事件绑定鼠标按钮,该事件将在<<< em>任何鼠标按钮按下或'&lt; button-1&gt;',(或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()

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文