Reputation: 315
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?
Upvotes: 1
Views: 1334
Reputation: 15098
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
Upvotes: 2
Reputation: 65323
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()
event
is needed for the concerned function<Control-v>
lambda
just before the function name call from
the button in order to call without issue by any means.Upvotes: 1