Dave Mathews
Dave Mathews

Reputation: 177

Cannot set focus() on an entry widget

When I try to set focus on an entry widget I receive an error,

Traceback (most recent call last):
  File "C:/PythonPrograms/Tkinter/test_case.py", line 13, in <module>
    entSearch.focus()
AttributeError: 'NoneType' object has no attribute 'focus'

From searching for other occurrences of this error on Stack overflow the fix appeared to be calling the grid method on a separate line.

entSearch = Entry(main, textvariable = text, width = 50, font='arial 12')
entSearch = entSearch.grid(row = 0, column = 1, sticky=W)

rather than

entSearch = Entry(main,
                  textvariable = text,
                  width = 50, 
                  font='arial 12').grid(row = 0, column = 1, sticky=W)

Unfortunately this fix is not working for me.

from tkinter import *

main = Tk()
main.title("Test Case")
main.geometry('750x750')
main.configure(background='ivory3')

text = StringVar()

entSearch = Entry(main, textvariable = text, width = 50, font='arial 12')
entSearch = entSearch.grid(row = 0, column = 1, sticky=W)

entSearch.focus()

main.mainloop()

Expected, Entry Widget would be in focus when the code is run.

But instead I receive the error

Traceback (most recent call last):
  File "C:/PythonPrograms/Tkinter/test_case.py", line 13, in <module>
    entSearch.focus()
AttributeError: 'NoneType' object has no attribute 'focus'

Upvotes: 1

Views: 1547

Answers (1)

user5407570
user5407570

Reputation:

The function you're looking for is focus_set() as opposed to focus(). A brief documentation on the focus_set() method.

EDIT:

Additionally, the line entSearch = entSearch.grid(row = 0, column = 1, sticky=W) is also causing problems. By default, the grid method does not return a value (only displays a given widget). Therefore, it returns None - you store this value in entSearch which means you can't 'focus' in on a None object. To solve this, simply remove the assignment and display your widget as such: entSearch.grid(row = 0, column = 1, sticky=W)

Upvotes: 5

Related Questions