首页 > 解决方案 > 如何在当前选项卡的文本小部件中插入文本?

问题描述

我最近了解了 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 ()

我添加了选项卡,但是当我尝试在检查函数中使用 insert 插入任何文本时,python 会出错。但问题并不完全是一个错误。我想在当前选项卡的文本小部件中插入文本。

标签: pythontkinter

解决方案


您需要创建一个存在于new_tab()函数之外的文本小部件——在您的代码中,它是一个局部变量,在函数返回后无法访问。

一种简单的方法(但不是最好的,因为全局变量是 bad)是使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()

作为比较,这里有一个后者的示例,它具有最少数量的全局变量,因为它基于面向对象的编程范式,即OOP方式来实现软件——即通过定义一个封装整个应用程序的类。

请注意,我还更改了imports 的执行方式,因为在大多数情况下,通配符导入也被认为是一种糟糕的编程实践(请参阅是否应避免通配符导入?)。

import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *


class MyApplication(tk.Tk):
    def __init__(self):
        super().__init__()
        self.nb = ttk.Notebook(self)
        self.nb.pack(fill=X)
        self.tab = 1
        self.text = None

        self.plus = tk.Button(self, text='+', command=self.new_tab)
        self.plus.pack(side=LEFT)

        self.check_button = tk.Button(self, text='check', command=self.check)
        self.check_button.pack(side=LEFT)

    def new_tab(self):
       self.text = tk.Text(self)
       self.text.pack()
       self.nb.add(self.text, text=("tab" + str(self.tab)))
       self.tab += 1

    def check(self):
       """ Insert text into Text widget if it exists. """
       if self.text:
           self.text.insert(END, 'new text\n')


app = MyApplication()
app.mainloop()

推荐阅读