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

如何在Tkinter中将两个独立窗口合并为一个,点击按钮加载对应界面

Tkinter多窗口合并为单窗口切换解决方案

核心思路

把原来独立窗口的功能界面改造为Frame容器的子类,不单独创建Tk或Toplevel根窗口,点击主窗口按钮时直接将功能Frame嵌入主窗口的对应区域即可。

第一步:改造employee功能模块(原main2.py,重命名为employee.py适配你的导入逻辑)

from tkinter import *
from PIL import ImageTk
import PIL.Image

class employeeClass(Frame):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.config(bg="white")
        # 所有控件的父级设为self(当前Frame),不需要再设置根窗口相关属性
        #-----Search-----
        SearchFrame=LabelFrame(self, text="Search Employee", bg="white")
        SearchFrame.place(x=250, y=20,width=600,height=70)

第二步:修改主窗口main.py代码,增加按钮和界面切换逻辑

from tkinter import *
from PIL import ImageTk
import PIL.Image
import os
from employee import employeeClass

class IMS:
    def __init__(self,root):
        self.root=root
        self.root.geometry("1350x700+0+0")
        self.root.title("IMS | Developed by Amit")
        self.root.config(bg="white")
        photo = PhotoImage(file = "images\\i1.png")
        self.root.iconphoto(False, photo)
        # 存储当前显示的功能界面实例
        self.current_frame = None
        
        # 主窗口左侧加功能按钮
        btn_employee = Button(self.root, text="员工管理", command=self.load_employee, font=("微软雅黑",14), bg="#2196f3", fg="white")
        btn_employee.place(x=20, y=20, width=150, height=50)
    
    def load_employee(self):
        # 先销毁之前显示的功能界面
        if self.current_frame is not None:
            self.current_frame.destroy()
        # 创建员工界面,挂载到主窗口
        self.current_frame = employeeClass(self.root)
        # 放在你原来独立窗口的对应位置,和原有布局保持一致
        self.current_frame.place(x=205, y=127, width=1055, height=480)

if __name__ =="__main__":
    os.system('python start.py')
    root = Tk()
    obj = IMS(root)
    root.mainloop()

逻辑说明

  • 改造后的employeeClass不再创建独立的根窗口,所有界面元素都承载在Frame容器上,可以直接嵌入任意父容器
  • 主窗口点击按钮时自动清空原有功能区域,加载新的功能Frame,完全实现在同一个窗口内切换不同功能,不需要弹出新窗口
  • 后续如果要新增其他功能界面,都按照同样的逻辑改造为Frame子类即可统一适配主窗口的切换规则

内容的提问来源于stack exchange,提问作者Amit Kumar Datta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:15:06