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

CustomTkinter销毁主窗口后无法创建新窗口的问题求助

问题分析与修复

核心错误原因

你代码里的致命问题是:在button_click_multifile函数中,先执行my_main.destroy()销毁主窗口,随后创建button3时却依然把父容器指定为已经被销毁的my_main,直接触发了can't invoke "frame" command: application has been destroyed错误。

另外,销毁主窗口后,CustomTkinter后台的一些定时任务(比如DPI缩放检查、动画回调)还在尝试调用已销毁窗口的命令,导致出现invalid command name类的报错。

修复后的代码

##################################################
# Throw up our Main Window
##################################################

import customtkinter
from customtkinter import CTk

my_main = customtkinter.CTk()  # create a new window
my_main.geometry("1000x600")
my_main.title("Data Analysis Utility")

customtkinter.set_appearance_mode("System")  # Modes: "System" (standard), "Dark", "Light"
customtkinter.set_default_color_theme("blue")  # Themes: "blue" (standard), "green", "dark-blue"

# Process Single File #
def button_click_singlefile():
    print("- You Selected Single File")

button1 = customtkinter.CTkButton(my_main, text="Process Single File", command=button_click_singlefile)
button1.grid(row=2, column=0, padx=20, pady=10)  # Put the button in a grid

# Process Multi File #
def button_click_multifile():
    print("- You Selected Multi File")
    # 隐藏主窗口而非直接销毁,避免后台任务报错
    my_main.withdraw()
    
    my_multi = CTk()  # create the Tk window like you normally do
    my_multi.geometry("1000x600")
    my_multi.title("Multi File Processing")
    
    # 将button3的父容器改为新窗口my_multi
    button3 = customtkinter.CTkButton(my_multi, text="new Multi")
    button3.grid(row=3, column=0, padx=20, pady=10)  # Put the button in a grid
    
    # 关闭新窗口时销毁主窗口,释放资源
    def on_multi_close():
        my_multi.destroy()
        my_main.destroy()
    
    my_multi.protocol("WM_DELETE_WINDOW", on_multi_close)
    my_multi.mainloop()

# add widgets to the first window
button2 = customtkinter.CTkButton(my_main, text="Process Multiple Files", command=button_click_multifile)
button2.grid(row=3, column=0, padx=20, pady=10)  # Put the button in a grid

my_main.mainloop()

关键修改点

  • 将创建button3时的父容器从my_main改为my_multi,确保控件绑定到新窗口
  • 使用my_main.withdraw()隐藏主窗口,代替直接destroy,避免CustomTkinter后台定时任务因窗口已销毁而报错
  • 添加WM_DELETE_WINDOW协议,在关闭新窗口时一并销毁主窗口,彻底释放资源

内容的提问来源于stack exchange,提问作者Dad and Beau

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:44:58