You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多模块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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 20:25:24