python - 如何在当前选项卡的文本小部件中插入文本?
问题描述
我最近了解了 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 会出错。但问题并不完全是一个错误。我想在当前选项卡的文本小部件中插入文本。
解决方案
您需要创建一个存在于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方式来实现软件——即通过定义一个封装整个应用程序的类。
请注意,我还更改了import
s 的执行方式,因为在大多数情况下,通配符导入也被认为是一种糟糕的编程实践(请参阅是否应避免通配符导入?)。
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()
推荐阅读
- razor - CheckBoxFor 可空布尔序列化
- python - 根据 Matplotlib 中的条件标记特定点
- java - if语句有问题,除了几秒钟外什么都没有得到,几秒钟后我应该得到几分钟和几天
- python - 我应该纠正什么错误?
- python - 感知器 - AND 运算符
- python - 是否可以完全按照本网站(toolslick)但使用 Python 将 HTML 转换为 JSON?
- java - 如何在 DAO 类中返回 (SELECT * FROM TABLE) 的结果
- reactjs - 我怎样才能得到
在反应羽毛笔中被识别? - processing - 处理 - 如何在制作另一个时阻止形状消失
- assembly - 我正在尝试在 MIPS 中编写一个函数,int mash(int x, int y):参数 x 和 y 在堆栈中传递