我最近了解了Notebook小部件。我想动态添加标签。
from tkinter import *
from tkinter import ttk
root = Tk ()
n = ttk.Notebook (root)
n.pack (fill = X)
tab = 1
def new_tab ():
global tab
text = Text (root)
text.pack ()
n.add (text, text = ("tab" + str (tab)))
tab += 1
def check ():
'' 'code to insert text into Text widget' ''
...
plus = Button (root, text = '+', command = new_tab)
plus.pack (side = LEFT)
check_button = Button (root, text = 'check', command = check)
check_button.pack (side = LEFT)
root.mainloop ()
我添加了选项卡,但是当我尝试在check函数中使用insert插入任何文本时,python给出了错误。但是问题不完全是一个错误。我想在当前标签的文本小部件中插入文本。
答案 0 :(得分:1)
您需要制作new_tab()
函数外部存在的文本小部件-在您的代码中,它是一个局部变量,函数返回后将无法访问它。
一种简单(但不是最好的)方法是使text
变量成为全局变量。更好的方法是使用类来封装应用程序的数据。
这是前者的一个例子:
from tkinter import *
from tkinter import ttk
root = Tk()
n = ttk.Notebook(root)
n.pack(fill=X)
tab = 1
text = None
def new_tab():
global tab
global text
text = Text(root)
text.pack()
n.add(text, text=("tab" + str(tab)))
tab += 1
def check():
""" Insert text into Text widget if it exists. """
if text:
text.insert(END, 'new text\n')
plus = Button(root, text='+', command=new_tab)
plus.pack(side=LEFT)
check_button = Button(root, text='check', command=check)
check_button.pack(side=LEFT)
root.mainloop()