Unexpected behavior with Python3 / Tkinter and two Listboxes bound to ListboxSelect event

泄露秘密 提交于 2019-12-02 12:47:47

By default, tkinter only allows one widget to hold the selection at a time. Thus, when you select something in your second listbox, the item selected in the first listbox is deselected. That causes your function to be called. When this happens, self.lb1.curselection()[0]) throws an error because the selection is empty.

A simple solution that allows the selection to remain unchanged in the first listbox when you select something in the second listbox is to set the exportselection option to False for both listboxes.

self.lb1 = tk.Listbox(self, exportselection=False)
...
self.lb2 = tk.Listbox(self, bg='orange', exportselection=False)

Based on this answer respective the comment on it from @BryanOakley:

The event doesn't represent a click, the event represents "the current item has changed" which may not always have an x and a y (ie: if you use the keyboard to change the current selection). event.widget.curselection() is what you should use.

So if the Listbox is destroyed, the new selection is as per the documentation

.curselection()
Returns a tuple containing the line numbers of the selected element or elements, counting from 0. If nothing is selected, returns an empty tuple. .

Therefore you get the IndexError as self.lb1.curselection()==(), which results in ()[0].

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