在每个标签上创建多个文本小部件
我需要什么: 在每个标签页上创建文本小部件。
我现在的代码是:
for i in range(len(result)):
tab[i] = ttk.Frame(tabControl)
tabControl.add(tab[i], text=i)
tabControl.pack(fill='both', expand=True)
for i in range(len(result)):
textwrite[i] = Text(tab[i])
textwrite[i].pack(fill='both', expand=True)
scrollbar_fortext[i] = Scrollbar(tab[i], orient='vertical', command=textwrite[i].yview)
scrollbar_fortext[i].pack(fill='both', expand=True, sticky=NS)
期望的效果: 每个标签页都有一个文本小部件。
实际的效果:
NameError: name 'textwrite' is not defined
2 个回答
0
在创建带索引的项目之前,你需要先初始化 tab
、textwrite
和 scrollbar_fortext
这几个变量,最好把它们设置为空的字典。还有,你应该只用一个 for
循环来生成 tab
、textwrite
和 scrollbar_fortext
。
在 for
循环之前或之后使用 tabControl.pack()
。另外,把变量名 tab
改成别的名字会更好。
1
如果你想声明一个动态变量,可以使用 dict
。因为你的代码不完整,我把 len(result) 设置为 5。你可以根据自己的需要修改这段代码。对于 '-sticky' 的选项,只有 -after、-anchor、-before、-expand、-fill、-in、-ipadx、-ipady、-padx、-pady 或 -side 这些选项,没有 NS 这样的选项。所以我把它去掉了。请根据需要进行修改。下面是代码的正确写法。
from tkinter import *
from tkinter import ttk
root = Tk()
root.geometry('700x500')
tabControl = ttk.Notebook(root, width=700)
tabControl.pack()
dct = {}
#for testing purpose I've given length of result as 5.Change the code accordingly.
for i in range(5):
dct[f'tab_{i}'] = ttk.Frame(tabControl)
tabControl.add(dct[f'tab_{i}'], text = f'{i}')
dct[f'scrollbar_fortext_{i}'] = Scrollbar(dct[f'tab_{i}'], orient='vertical')
dct[f'scrollbar_fortext_{i}'].pack(fill='both', expand=True)
root.mainloop()