Default to and select first item in Tkinter listbox

与世无争的帅哥 提交于 2019-12-05 07:53:43

The simplest solution is to generate the <<ListboxSelect>> event at the same time that you change the selection:

def updateoptions(self, *args):
    ...
    self.listbox.select_set(0) #This only sets focus on the first item.
    self.listbox.event_generate("<<ListboxSelect>>")
    ...
# add before .mainloop()
self.listbox.selection_set( first = 0 )

EDIT#1 2014-08-21 13:50 [UTC+0000]

Tkinter.Listbox()-es have quite a complex MVC-Model-Part behaviour. Thus its Controller-Part .methods() are bit more complex subject to handle.

The Listbox() default select-mode allows only a single item to be selected, but the select-mode argument supports four settings: SINGLE, BROWSE, MULTIPLE, and EXTENDED ( the default is BROWSE ). Of these, the first two are single selection modes, and the last two allow multiple items to be selected.

These modes vary in subtle ways.

For instance, BROWSE is like SINGLE, but it also allows the selection to be dragged.

Clicking an item in MULTIPLE mode toggles its state without affecting other selected items.

And the EXTENDED mode allows for multiple selections and works like the Windows file explorer GUI—you select one item with a simple click, multiple items with a Ctrl-click combination, and ranges of items with Shift-click-s.

Multiple selections can be programmed with code of this sort:

listbox = Listbox( aWindow, bg = 'white', font = ( 'courier', fontsz ) )
listbox.config( selectmode = EXTENDED )                         # see above
listbox.bind( '<Double-1>', ( lambda event: onDoubleClick() ) ) # a lambda-wrapped CallBackHANDLER()
# onDoubleClick: get messages selected in listbox               # not listed here
selections = listbox.curselection()                             # tuple of digit-string(s), aTupleOfSTRINGs, where digit-string(s) range from { 0, 1, .., N-1 }
selections = [ int( x ) + 1 for x in selections ]               # transform string(s) to shifted int(s), make 'em { 1, 2, .., N }

When multiple selections are enabled, the .curselection() method returns a list of digit strings giving the relative numbers of the items selected, or it returns an empty tuple if none is selected.

Beware this method always returns a tuple of digit strings, even in single selection mode.

Thus symmetrically the Listbox().selection_set() method has to feature-rich so as to be able to configure all possible states for the value of <aSelectionSET>.

Q.E.D. above in the initial post.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!