多模块Python Tkinter中跨模块调用Text.insert方法的最简实现
跨模块调用Tkinter Text组件的insert方法问题及解决方案
我出于兴趣开发一个Python小项目,最初把代码写在单个文件里,导致文件庞大杂乱,于是拆分成多个模块开发。拆分后其他功能正常,但遇到了无法在test.py模块中调用gui_test.py里的Text.insert方法的问题。
初始代码
gui_test.py
from tkinter import * import threading from test import test_fun def t_test(): t0 = threading.Thread(target=test_fun) t0.start() if __name__ == "__main__": root = Tk() root.title(f"test_gui") root.geometry("355x280") txt = Text(root, width=50, height=10, wrap=WORD) # log txt.place(x=0, y=20) txt.config(state=NORMAL) btn1 = Button(root, text="test_button", command=t_test) btn1.place(x=5, y=160) root.mainloop()
test.py
import time def test_fun(): sec = 0 while True: txt.insert(END, f"{sec}\n") sec += 1 time.sleep(1)
请问如何在test.py中发送文本并显示在gui_test.py的Text组件中?寻求最简实现方案。
解决后的代码
gui_test.py
from tkinter import * import threading from test import test_fun def t_test(): t0 = threading.Thread(target=test_fun, args=(root,), daemon=False) t0.start() if __name__ == "__main__": root = Tk() root.title(f"test_gui") root.geometry("355x280") root.txt = Text(root, width=50, height=10, wrap=WORD) # log root.txt.place(x=0, y=20) root.txt.config(state=NORMAL) btn1 = Button(root, text="test_button", command=t_test) btn1.place(x=5, y=160) root.mainloop()
test.py
import time from tkinter import * def test_fun(widget): sec = 0 while True: widget.txt.insert(END, f"{sec}\n") widget.txt.update() widget.txt.see(END) sec += 1 time.sleep(1)
内容的提问来源于stack exchange,提问作者HotterThanKimchi
相关产品推荐
相关产品推荐

