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

无法从MainFrame(ttk.Frame)类关闭tkinter应用,求解决方案

代码存在的问题

  • MainFrame初始化方法中额外实例化了一个新的App对象,和实际运行的主窗口不是同一个实例,完全多余
  • MainFrame的exit_test方法尝试访问的app是初始化方法内的局部变量,方法作用域无法访问该变量,即使能访问操作的也是错误的新App实例
  • App类中定义的exit_app方法缺少必选的self参数,且内部逻辑错误,Tk实例关闭不需要调用container.exit,直接调用destroy方法即可

修复后完整代码

import tkinter as tk
from tkinter import ttk


class MainFrame(ttk.Frame):
    def __init__(self, container):
        super().__init__(container)

        self.style2 = {'fg': 'black', 'bg': '#e95420', 'activebackground': 'coral', 'activeforeground': '#2f2f2f'}
        
        self.exit=tk.Button(self , compound=tk.RIGHT, text='exit', width=20, relief="solid")
        self.exit['command'] = self.exit_test
        self.exit.pack(expand=False, padx=0, pady=100, ipadx=10, ipady=10, side=tk.BOTTOM)
        self.exit.configure(self.style2)
        self.pack()

    def exit_test(self):
        # self.master就是传入的主窗口App实例,直接调用destroy关闭整个应用
        self.master.destroy()

class StatusBar(tk.Frame):   
    def __init__(self, container):
        super().__init__(container)
         
        self.variable=tk.StringVar()
        self.variable.set("add the current time here")        
        self.label=tk.Label(self, bd=0, relief="solid", height="2", width="1500", textvariable=self.variable, foreground="white", background='#2f2f2f', font=('helvetica',9))                       
        self.label.pack()       
        self.pack(fill="x", side="bottom", ipady=0, padx=0, pady=0)


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.geometry("1500x1100")


if __name__ == "__main__":
    app = App()
    frame = StatusBar(app)
    frame = MainFrame(app)
    app.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:45:04