How to set focus for Tkinter widget?

I have a simple Python + Tkinter application that displays a list of 10 elements:

import Tkinter, ttk list = ttk.Treeview( Tkinter.Tk() ) list.pack( fill = Tkinter.BOTH, expand = 1 ) items = [ list.insert( '', 'end', text = str( i ) ) for i in range( 10 ) ] list.selection_set( items[ 0 ] ) list.focus_set() # This is not working - list has no focus :( Tkinter.mainloop() 

Is it possible to change it, so that after the application starts, the list will have focus, and I can move the selection using the up and down arrows? After starting the application, the application window has focus, but I can not move the selection with arrows until we click the list with the mouse :( I tried different combinations of focus_set() and focus_force() , but it does not work.

Tested with Python 2.7 on Windows 7, OSX 10.7 and Ubuntu 12.04

UPDATE

If "Treeview" is changed to another widget, for example, to "Button", the focus works. Therefore, it seems that I set the focus for Treeview to be somehow wrong.

+7
source share
1 answer

Finally, a solution was found - it seems that the Treeview widget should be set focus two times: first for the widget itself, and the second for the element:

 list.selection_set( items[ 0 ] ) list.focus_set() list.focus( items[ 0 ] ) # this fixes a problem. 
+8
source

All Articles