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

如何在Tkinter中实现关闭除初始主窗口外其余所有打开窗口的功能

实现思路
  • 首先修正原代码的核心错误:子窗口不要创建新的Tk()实例,改用Toplevel控件(Tk()是主窗口实例,一个程序只应该保留一个)
  • 新增全局列表存储所有已打开的子窗口实例
  • 主窗口新增Home按钮,点击时遍历列表销毁所有子窗口、清空列表即可回到初始主菜单状态
  • 移除每个子窗口多余的mainloop()调用,仅保留主窗口的事件循环即可
  • 同步修复原代码的两个小问题:font参数语法错误、子窗口图片被GC回收导致无法显示的问题
完整可运行代码
from os import system
from tkinter import *
from PIL import ImageTk, Image

# 存储所有打开的子窗口
open_windows = []

# Home按钮回调:关闭所有子窗口
def back_to_home():
    for win in open_windows:
        win.destroy()
    open_windows.clear()

mainmenu = Tk()
mainmenu.title("CAU 310 GUIDE MAP")
mainmenu.geometry("1280x800+0+0")

canvas = Canvas(mainmenu, width = 1280, height = 800)
canvas.pack(fill='both', expand = True)

canvas.create_text(640, 250, text = 'WELCOME', font=('times', 45))

btnclassroom = Button(mainmenu, padx=5, pady=5,text="Classroom", font="times 30", command=selectfloor)
btnclassroom.place(x=140, y=570)

# 新增Home按钮,可自定义位置和样式
btnhome = Button(mainmenu, padx=5, pady=5,text="Home", font="times 30", command=back_to_home, bg='red', fg='white')
btnhome.place(x=1000, y=570)


def selectfloor():
    # 子窗口改用Toplevel
    floor_win = Toplevel(mainmenu)
    floor_win.title("DESTINATION")
    floor_win.geometry("1280x800+0+0")
    floor_win.config(bg='white')
    # 子窗口加入统一管理列表
    open_windows.append(floor_win)

    canvas = Canvas(floor_win, width = 1280, height = 800)
    canvas.pack(fill='both', expand = True)
    
    canvas.create_text(640, 150, text = 'Select floor of classroom', font='Arial 40')

    btn7=Button(floor_win, padx=4, pady=4, text="7F", font="Arial 42 bold", command=floor7)
    btn7.place(x=160-5, y=490)

def floor7():
    f7_win = Toplevel(mainmenu)
    f7_win.title("FLOOR 7")
    f7_win.geometry("1280x800+0+0")
    open_windows.append(f7_win)

    canvas = Canvas(f7_win, width = 1280, height = 800)
    canvas.pack(fill='both', expand = True)

    canvas.create_text(640, 150, text = 'Select classroom No.', font='Arial 40')

    btn702=Button(f7_win, padx=3, pady=3, text="No.702", font="Arial 38 bold", command=room702)
    btn702.place(x=100+220*1, y=240)

def room702():
    r702_win = Toplevel(mainmenu)
    r702_win.title("Elevator 1")
    r702_win.geometry("1280x800+0+0")
    open_windows.append(r702_win)

    lobby = ImageTk.PhotoImage(Image.open("1F_elevator1.jpg"), master=r702_win)

    canvas = Canvas(r702_win, width = 1280, height = 800)
    canvas.pack(fill='both', expand = True)

    canvas.create_image(0, 0, image=lobby,anchor = "nw")
    # 保存图片引用避免被GC回收导致图片不显示
    canvas.lobby = lobby

mainmenu.mainloop()
功能验证

依次点击Classroom、7F、No.702打开3个子窗口后,点击主窗口的Home按钮,所有子窗口会被一次性关闭,仅保留显示WELCOME的主菜单窗口,完全符合需求。

内容的提问来源于stack exchange,提问作者Sangmin Kim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:54:03