【python】【tkinter】向scrolledtext插入信息,优化代码

目标:其他类在运行中产生的信息,依次插入文本框
说明:运行都在【class Main】完成,不要并入【class App】这个类下
现行方案:global app_text
请教问题:global理论上可能影响性能,是否有其他更优方案完成上述目标?谢谢

import time
import tkinter as tk
from tkinter import scrolledtext


# 目标:其他类在运行中产生的信息,依次插入文本框
# 说明:运行都在【class Main】完成,不要并入【class App】这个类下
# 现行方案:global app_text
# 请教问题:global理论上可能影响性能,是否有其他更优方案完成上述目标?谢谢


class App:  # 用于交互
    def __init__(self):
        self.window = tk.Tk()
        self.widget()
        self.window.mainloop()

    def widget(self):
        button = tk.Button(self.window, text="点我干饭", command=self.go)
        button.pack()

        global app_text  # 现有方案
        app_text = scrolledtext.ScrolledText(self.window)
        app_text.pack()

    def go(self):
        Main()


class Main:  # 用于运算
    def __init__(self):
        self.a1()
        self.a2()

    def a1(self):
        time.sleep(1)
        app_text.insert("insert", "干饭人老汤先吃了三碗\n")  # 插入信息
        app_text.update()

    def a2(self):
        time.sleep(1)
        app_text.insert("insert", "干饭人老汤又又又吃了第四碗\n\n")  # 插入信息
        app_text.update()


App()

这样应该可以,和你之前的代码运行效果是一样的



class App:  # 用于交互
    def __init__(self):
        self.window = tk.Tk()
        self.widget()
        self.window.mainloop()

    def widget(self):
        button = tk.Button(self.window, text="点我干饭", command=self.go)
        button.pack()
        # global app_text  # 现有方案
        self.app_text = scrolledtext.ScrolledText(self.window)
        self.app_text.pack()

    def go(self):
        Main(self.app_text)


class Main:  # 用于运算
    def __init__(self, app_text):
        self.a1(app_text)
        self.a2(app_text)

    def a1(self, app_text):
        time.sleep(1)
        app_text.insert("insert", "干饭人老汤先吃了三碗\n")  # 插入信息
        app_text.update()

    def a2(self, app_text):
        time.sleep(1)
        app_text.insert("insert", "干饭人老汤又又又吃了第四碗\n\n")  # 插入信息
        app_text.update()


App()