简体   繁体   中英

Can you bind a button as well as a key press to a function in tkinter?

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

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/

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