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

使用Tkinter开发单页面应用能否拆分为两个模块以简化代码?

这个拆分模块的需求完全可以实现,你当前代码运行报错的核心原因是a2.py中的函数无法直接访问a1.py中定义的主窗口root对象,只要通过参数传递的方式把root传入模块2的函数即可解决。

调整后的代码

模块1(a1.py)

from tkinter import *
from a2 import create_frame


root=Tk()
root.title("voccabulary journel")
root.geometry("700x450")
root.configure(bg='#ff8000')

# 将创建好的主窗口对象作为参数传入模块2的函数
create_frame(root)

root.mainloop()

模块2(a2.py)

from tkinter import *

# 函数增加入参root,接收外部传入的主窗口对象
def create_frame(root):
    Grid.rowconfigure(root,0,weight=1)
    Grid.columnconfigure(root,0,weight=1)
    Grid.columnconfigure(root,1,weight=3)

    frame1=Frame(root,background='black')
    frame1.grid(row=0,column=0,sticky='nsew')

    frame2=Frame(root,background='white')
    frame2.grid(row=0,column=1,sticky='nsew')

    labeltry1=Label(frame1, text='testing')
    labeltry1.pack()

    labeltry2=Label(frame2,text='tersting')
    labeltry2.pack()

额外提示:建议不要使用frame作为自定义函数名,避免和Tkinter内置的Frame类命名冲突。后续如果要扩展更多页面组件,都可以按照「父容器作为参数跨模块传递」的逻辑拆分代码,保持结构清晰。

内容的提问来源于stack exchange,提问作者dead day

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:06:03