Python tkinter:处理多个选项卡

use*_*731 5 python user-interface tkinter

好的,我有这个简单的代码:

import tkinter.filedialog
from tkinter import *
import tkinter.ttk as ttk

root = Tk()
root.title('test')

nb = ttk.Notebook(root)
nb.pack(fill='both', expand='yes')

f1 = Text(root)
f2 = Text(root)
f3 = Text(root)

nb.add(f1, text='page1')
nb.add(f2, text='page2')
nb.add(f3, text='page3')

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

我只是想知道,在 tkinter 中处理带有文本的多个选项卡的最佳方法是什么?就像如果我想删除“page2”上的所有文本或在“page3”上插入一些内容,我该怎么做?

A. *_*das 3

f1您已经在、f2和中引用了文本小部件f3,因此您可以直接调用它们的方法:

f2.delete(1.0, 'end') # erase all the text on the 2nd tab

f3.insert('end', 'hello, world') # insert text on the 3rd tab
Run Code Online (Sandbox Code Playgroud)

您可能还想将小部件添加到列表中,以防您想对所有小部件执行相同的操作。

texts = [f1, f2, f3]
for text in texts:
    text.delete(1.0, 'end')
Run Code Online (Sandbox Code Playgroud)