简体   繁体   English

如何为 tkinter 中的函数添加键盘快捷键

[英]How do I add a keyboard shortcut to a function in tkinter

I did some research in Tkinter and found the root.bind('<Control-Key-whatever key', function).我在 Tkinter 中做了一些研究,发现了 root.bind('<Control-Key-whatever key', function)。

I wanted to add this to an application I was making.我想将此添加到我正在制作的应用程序中。

I made a button and I want it to perform a function when I click a certain key combination.我做了一个按钮,当我点击某个组合键时,我希望它执行一个功能。

Here is my code:这是我的代码:

from tkinter import *

root = Tk()
root.geometry("600x600")

def printFunction():
    print("Hello World")

root.bind('<Control-Key-v>', printFunction)

button = Button(root, text="click here", command=printFunction)
button.pack()

root.mainloop()

So when I click the button the function should perform, and when I click Ctrl+v the function should perform.因此,当我单击按钮时,函数应该执行,而当我单击 Ctrl+v 时,函数应该执行。 The button works fine, but the key combination does not work.该按钮工作正常,但组合键不起作用。 How do I fix this?我该如何解决?

It should be something like它应该是这样的

root.bind('<Control-v>', printFunction)

But keep in mind, this will again throw another error, because you have to pass event as a parameter to the function.但请记住,这将再次引发另一个错误,因为您必须将event作为参数传递给函数。

def printFunction(event=None):
    print("Hello World")

Why event=None ?为什么event=None This is because your button is also using the same function as a command but without any arguments passed to it on declaration.这是因为您的按钮也使用与command相同的功能,但没有在声明时传递给它的任何参数。 So to nullify it, this is a workaround.因此,要使其无效,这是一种解决方法。

Alternatively, your could also pass something like *args instead of event :或者,您也可以传递类似*args而不是event

def printFunction(*args):
    print("Hello World")

Hope you understood better.希望你能更好地理解。

Cheers干杯

You can use您可以使用

from tkinter import *

root = Tk()
root.geometry("600x600")

def printFunction(event):
    print("Hello World")

button = Button(root, text="click here", command=lambda:printFunction(None))
root.bind('<Control-v>', printFunction)
button.pack()
root.mainloop()
  • Argument event is needed for the concerned function相关函数需要参数event
  • Event name should be converted to <Control-v>事件名称应转换为<Control-v>
  • Don't forget to add lambda just before the function name call from the button in order to call without issue by any means.不要忘记在按钮的函数名称调用之前添加lambda ,以便以任何方式调用都没有问题。

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

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