FAQ Index - Search - Recent Changes - Everything - Add entry

<< Previous Entry | FAQ Entry 5.10 | Next Entry >>

5.10. How do I focus a widget? How do I focus it before its toplevel window is shown?

Use the widget's grab_focus() method. Note that the widget must be added to a window or dialog before calling grab_focus, since (perhaps a bit unexpectedly) the focused widget is a property of a *toplevel window* and not its child widgets. In other words:

 e = gtk.Entry()
 e.show()
 e.grab_focus()
 w = gtk.Window()
 w.add(e) # oh-oh, added after grab_focus()
 w.show()
would NOT work, but

 e = gtk.Entry()
 w = gtk.Window()
 w.add(e)
 e.grab_focus() # called after add
 w.show_all() # no need for e.show() in this case
will work as expected (using idle_add() to call grab_focus() is naughty and we know that python hackers are never naughty :-P ).

PyGTK FAQ Wizard | PyGTK Homepage | Feedback to faq at pygtk.org