Tkinter切换标签页时Listbox首次选择触发索引错误的问题求助
Tkinter切换标签页时Listbox首次选择触发索引错误的问题求助
我做了一个带标签页的界面,每个标签页上都有Listbox组件。现在遇到个头疼的问题:切换标签页后,在新标签页的Listbox里第一次选择选项时会触发IndexError(索引错误),但之后再选任何选项都能正常识别。我把这个问题简化成了下面的示例代码,能复现同样的错误:
import tkinter as tk from tkinter import ttk class App(tk.Tk): """basic class to replicate tab-switching error""" def __init__(self): """exactly what it looks like""" super().__init__() self.items = {'Alphic': ["A","B","C",'c','d'], 'Numera':['1','2','3','4','5','6']} self.selection = tk.StringVar() self.main = tk.Frame() self.tabs = ttk.Notebook(self.main) self.make_tabs() self.main.pack() def make_tabs(self): """create all tabs in collected data""" def make_tab(f, data): 'create single tab' frame = ttk.Frame(self.tabs) select = tk.Listbox(frame, width = 20, height = 8) def update_selection(*_): try: index = [i for i in select.curselection()][0] except IndexError: index = "This Error Right Here" print(index) for n,k in enumerate(data): print("inserting", n) select.insert(n+1,k) select.pack() frame.pack() select.bind('<<ListboxSelect>>', update_selection) return frame for i, k in self.items.items(): self.tabs.add(make_tab(i,k), text=i) self.tabs.pack() if __name__ == "__main__": a = App() a.mainloop()
这个问题在我正在开发的一个大型程序里造成了很危险的bug——错误会导致之前选中标签页的索引“串”到新标签页里。我已经确认就是这个Listbox的问题导致的。
我还试着研究了触发事件(Event)的内容,想看看能不能找到线索,但什么有用的信息都没发现。
备注:内容来源于stack exchange,提问作者Starscream
相关产品推荐
相关产品推荐

