Reputation: 27
I am trying to make a small program where a user can click a button and it prints text, but if the user clicks the space bar it will also print the text. I know how to connect a button and a function using "command=....." not sure how to bind keys though. any help would be appreciated.
import tkinter as tk
root = tk.Tk()
def yes():
print("yes")
okbtn = tk.Button(text='OK', font=("Helvetica",50), bg = "red", command=yes, width=10, height=3)
okbtn.pack()
root.mainloop()
Upvotes: 1
Views: 1820
Reputation: 3285
You can bind functions to keys, using the .bind
method which takes a key (or combination of modifiers and keys) and a function to execute
So in your example, adding the line below, would bind the yes
function to the spacebar
root.bind('<space>', lambda event: yes())
Note that any bound function will take a tkinter event
as argument (which contains mouse coordinates, time of execution, reference to master widget, and more) - I have ignored the event argument in this case, by making a dummy lambda. However, it can often be useful
Here is an example of a function where the event is actually being used (prints the mouse position at the time where the function was called)
def motion(event):
print("Mouse position: (%s %s)" % (event.x, event.y))
You can check out this link for more information about even binding in tkinter https://www.pythontutorial.net/tkinter/tkinter-event-binding/
Upvotes: 2