简体   繁体   中英

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

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. 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.

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

Why 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. So to nullify it, this is a workaround.

Alternatively, your could also pass something like *args instead of 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 name should be converted to <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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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