【python】封装为类的tkinter,怎么在类外把信息写到Tkinter的text控件中

封装为类的tkinter,怎么在类外把信息写到Tkinter的text控件中

import tkinter as tk
from tkinter import scrolledtext


class App:
    def __init__(self, window):
        self.window = window
        self.window.title("main")
        self.window.geometry("600x300")
        self.labelframe()
        self.text_insert()

    def labelframe(self):
        lf = tk.LabelFrame(
            self.window, text="运行信息", font=("微软雅黑", 10, "bold"), padx=10, pady=10
        )
        lf.place(x=20, y=20)

        text = scrolledtext.ScrolledText(lf, height=5, width=65, font=("微软雅黑", 10))
        text.grid()

        self.text = text

    def text_insert(self):
        self.text.insert("end", "Part_1:这是类内写入的信息... \n")


# 怎么在类外把信息写到Tkinter的text控件中
message = "Part_2:这条信息,在类外写入Tkinter text控件"


root = tk.Tk()
app = App(root)
root.mainloop()
import tkinter as tk
from tkinter import scrolledtext
 
class App:
    def __init__(self, window):
        self.window = window
        self.window.title("main")
        self.window.geometry("600x300")
        self.labelframe()
        self.text_insert()
    def labelframe(self):
        lf = tk.LabelFrame(
            self.window, text="运行信息", font=("微软雅黑", 10, "bold"), padx=10, pady=10
        )
        lf.place(x=20, y=20)
        text = scrolledtext.ScrolledText(lf, height=5, width=65, font=("微软雅黑", 10))
        text.grid()
        self.text = text
    def text_insert(self):
        self.text.insert("end", "Part_1:这是类内写入的信息... \n")

    def change(self,txt):
        self.text.insert("end",txt)
 
# 怎么在类外把信息写到Tkinter的text控件中
message = "Part_2:这条信息,在类外写入Tkinter text控件"
 
root = tk.Tk()
app = App(root)
app.change(message)
root.mainloop()

img

18行已经提供了对象指针了。。。直接在root.mainloop前加
app.text.insert("end",message)
就可以了。。。

img
考虑到界面刷新,如果里面有10个文本,总不能写10个change方法吧。。。不美观且重复代码也多。
可以理解为self.text = text为常规包装类时候声明的全局对象。。
当然这里没有public private protected的说法。仅仅只是局部对象和全局对象的区别,如果不写这个,类内其他方法也访问不到这个对象。