用 threading 模块创建了一个新的线程来运行循环,以避免阻塞 GUI 线程,从而实现同时显示界面和循环输出信息的目的。
现在,循环会在新的线程中运行,并将输出信息通过回调函数传递给 display_print_output() 方法,在界面上显示出来。
请在运行时确保 module.py 和 main.py 文件在同一目录下,并确保使用 main.py 执行程序。界面会显示出循环的输出信息,同时循环会一直在后台运行。
# module.py
import time
def my_loop(callback):
counter = 0
while True:
message = "Hello" + str(counter)
callback(message)
counter += 1
time.sleep(1)
# main.py
import tkinter as tk
import threading
import module
class GUI:
def __init__(self):
self.root = tk.Tk()
self.textbox = tk.Text(self.root)
self.textbox.pack()
def display_print_output(self, message):
self.textbox.insert(tk.END, message + "\n")
self.textbox.see(tk.END)
def start_loop(self):
threading.Thread(target=module.my_loop, args=(self.display_print_output,)).start()
gui = GUI()
gui.start_loop()
gui.root.mainloop()