Edyoucaterself
Edyoucaterself

Reputation: 167

How do I set focus to an entry widget from a function

I have a class with several functions, one of them throws an exception and I would like to set the focus back to the entry widget it is validating. calling:

self.entryWidget.set_focus()

returns an AttributeError:

'App' object has no attribute 'entryWidget'

How can should I refer to this widget outside of __init__?

class App:
    def __init__(self,master):
        calcframe = Frame(master)
        calcframe.pack()
        self.vol = DoubleVar()
        entryWidget = Entry(calcframe, textvariable=self.vol)
        entryWidget.grid(row=1, column=1, sticky=W)
        entryWidget.focus()

    def updateSIP(self):
        try:
            volume = self.vol.get()
        except:
            self.entryWidget.set_focus()
root = Tk()
root.wm_title('title')
app = App(root)
root.mainloop()

Upvotes: 0

Views: 825

Answers (1)

user2555451
user2555451

Reputation:

The problem is that you are not making entryWidget an attribute of App.

To do this, place self. before it:

def __init__(self,master):
    calcframe = Frame(master)
    calcframe.pack()
    self.vol = DoubleVar()
    self.entryWidget = Entry(calcframe, textvariable=self.vol)
    self.entryWidget.grid(row=1, column=1, sticky=W)
    self.entryWidget.focus()

Now, entryWidget is an attribute of App and can be accessed through self.

Upvotes: 2

Related Questions