简体   繁体   中英

Problems with Tkinter Binding to enter/return

My program:

#!/usr/bin/python
from Tkinter import *
class App:
    def __init__(self,master):
        frame = Frame(master,width = 100,height = 100)
        frame.bind('<Return>',self.ret)
        frame.pack()

    def ret(self):
        print "You pressed enter"

root = Tk()
app = App(root)
root.mainloop()  

It opens up the window but when I press return or enter it doesn't do anything.

This is because you have to set the focus on the frame to respond to the event:

frame = Frame(master,width = 100,height = 100)
frame.focus_set()

By the way, callbacks receive a Tkinter event as an argument, so ret should be defined as def ret(self, event) , or bind the event with a lambda function and don't use the argument:

frame.bind('<Return>', lambda e: self.ret())

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