Question

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.

Was it helpful?

Solution

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())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top