如何在tkinter ttk Notebook指定位置插入选项卡并解决索引越界报错
报错原因
- ttk.Notebook的选项卡索引从0开始计数,有效插入索引范围为
0 ≤ 索引 ≤ 当前已存在的选项卡总数:你首次调用fileexplore_tab(2)时,Notebook内仅存在1个Translator选项卡,最大有效插入索引为1,传入2直接超出范围触发报错。 - 要实现克隆入口固定停靠在末尾的需求,逻辑应该是先将克隆入口选项卡添加到Notebook末尾,后续所有克隆生成的新选项卡都插入到
len(tabs.tabs())-1的位置,这个位置就是克隆入口的前一位,插入完成后克隆入口依然保持在最后一位。
修正后参考代码
from tkinter import * from tkinter import ttk, messagebox as msg from widgets.translate import Translator from widgets.explore import FileExplorer root = Tk() root.title('Widgets') tabs = ttk.Notebook(root, width=900, height=350) tabs.pack(fill='both', expand=1, pady=(5, 0)) tr = ttk.Frame(tabs) tr_frame = ttk.Frame(tr) tr_frame.pack(fill=Y) tabs.add(tr, text='Translator') Translator(tr_frame) # 先添加固定在末尾的克隆入口选项卡 clone_tab = ttk.Frame(tabs) tabs.add(clone_tab, text='+ 新建') # 可以在这里给clone_tab绑定<<NotebookTabChanged>>事件,点击时触发克隆逻辑 explorers=0 translators=0 def fileexplore_tab(): global explorers fl_explore = ttk.Frame(tabs) # 插入到当前最后一个(也就是克隆入口)的前一位 insert_pos = len(tabs.tabs()) - 1 tabs.insert(insert_pos, fl_explore, text='File Explorer') FileExplorer(fl_explore) explorers += 1 # 测试调用 fileexplore_tab() fileexplore_tab() print(len(tabs.tabs())) root.mainloop()
注意事项
- 不要硬编码插入索引,所有插入位置都通过
len(tabs.tabs())动态计算,避免后续选项卡数量变化后再次出现越界问题。 - 如果你的克隆入口是后续添加的,只要保证插入新选项卡时,位置参数取值不超过当前选项卡总数即可。
内容的提问来源于stack exchange,提问作者a_programmer_on_stackoverflow
相关产品推荐
相关产品推荐

