Search code examples
pythonpython-3.xtkinterkey-bindings

<Return> Key binding doesn't work at all


I'm coding a simple gui with tkinter and python. Here's the code:

from tkinter import *

class migrate_tk(Tk):
    def __init__(self, parent):
        Tk.__init__(self, parent)
        self.geometry("400x400")
        self.parent = parent        
        self.initialize()

    def initialize(self):           
        self.grid()                 

        self.entry = Entry(self)                            
        self.entry.grid(column=0, row=0, sticky='EW')       
        #~ self.entry.focus_set()
        self.entry.bind("<Return>", self.OnPressEnter)        
        #~ self.bind('<Return>', self.OnPressEnter)

        label = Label(self, anchor="w", fg="white", bg="blue")
        label.grid(column=0, row=1, columnspan=2, sticky="EW")

        self.grid_columnconfigure(0, weight=1)          

        self.resizable(True, False)                     

    def OnPressEnter(self,event):
        print ("You pressed enter")
        if self.label["bg"] == "blue":
            self.label["bg"] = "yellow"
        else: self.label["bg"] = "blue"


if __name__ == "__main__":
    app = migrate_tk(None)
    app.title('app') 
    app.mainloop()

The problem is that pressing the return key, it doesn't print anything (obviously i run it into a terminal) Thanks!


Solution

  • The problem you might be getting is:

    AttributeError: 'tkapp' object has no attribute 'label'
    

    & the reason for that is: you have to do this while declaring label:

    self.label = Label(self, anchor="w", fg="white", bg="blue")
    self.label.grid(column=0, row=1, columnspan=2, sticky="EW")
    

    Down below you were using label as an instance of class migrate_tk but not when you declared it

    The enter widget doesn't get focus automatically,so when you press Enter without selecting the widget,it doesn't do anything.

    What you need to do is un-comment the code:

    self.entry.focus_set()
    

    & It will work fine after that.