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

如何在Tkinter中点击Continue按钮后销毁窗口或移除动态复选框

解决Tkinter程序Continue按钮的两种需求

以下针对你提出的两种需求,给出具体的代码修改方案:

方案一:销毁当前窗口并创建新窗口

修改_continue方法,在用户确认后销毁当前主窗口,并启动新的应用窗口,同时调整主函数逻辑支持重复创建窗口:

import tkinter as tk
from tkinter import ttk
from tkinter import messagebox


def main():
    app = Application()
    app.mainloop()


class Application(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Simple App")
        self.geometry('500x300')

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        frame = InputForm(self)
        frame.grid(row=0, column=0, sticky="nsew", padx=5, pady=5)


class InputForm(ttk.Frame):
    def __init__(self, parent):
        super().__init__(parent)

        self.columnconfigure(0, weight=1)
        self.checkboxes = {}  # 存储复选框对应的变量
        self.count = 0
        self.dict_keys = ["Item1", "Item2", "Item3", "Item4"]
        self.selected = {}

        # 创建复选框
        for item in self.dict_keys:
            self.create_check_box(item)

        self.entry_btn = ttk.Button(self, text="Add", command=self.add_to_list)
        self.entry_btn.grid(row=0, column=1)

        self.entry_btn2 = ttk.Button(self, text="Clear", command=self.clear_list)
        self.entry_btn2.grid(row=0, column=2)

        self.entry_btn3 = ttk.Button(self, text="Continue", command=self._continue)
        self.entry_btn3.grid(row=0, column=3)

    def create_check_box(self, item):
        int_var = tk.IntVar(value=0)  # 默认未选中
        checkbutton = ttk.Checkbutton(self, text=item, variable=int_var, command=lambda: self.check_state(item))
        checkbutton.grid(row=self.count + 1, column=0, sticky='w')
        self.checkboxes[item] = int_var
        self.count += 1

    def check_state(self, item):
        state = self.checkboxes[item].get()
        print(f"复选框 '{item}' 状态: {state}")

    def add_to_list(self, _event=None):
        selected_items = [item for item, var in self.checkboxes.items() if var.get() == 1]
        print(f"选中项: {selected_items}")

    def clear_list(self):
        for var in self.checkboxes.values():
            var.set(0)

    def _continue(self):
        if messagebox.askyesno(title='确认继续?', message='确定要继续吗?'):
            # 保存选中内容
            self.selected = {key: 'Selected' for key, value in self.checkboxes.items() if value.get() == 1}
            print(self.selected)
            # 销毁当前主窗口
            self.master.destroy()
            # 启动新的应用窗口
            main()
            
if __name__ == "__main__":
    main()

方案二:移除当前窗口中的所有复选框

先修改create_check_box方法,将复选框控件本身存入字典方便后续销毁,再在_continue方法中遍历销毁所有复选框:

import tkinter as tk
from tkinter import ttk
from tkinter import messagebox


def main():
    app = Application()
    app.mainloop()


class Application(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Simple App")
        self.geometry('500x300')

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        frame = InputForm(self)
        frame.grid(row=0, column=0, sticky="nsew", padx=5, pady=5)


class InputForm(ttk.Frame):
    def __init__(self, parent):
        super().__init__(parent)

        self.columnconfigure(0, weight=1)
        self.checkboxes = {}  # 存储复选框控件和对应变量: {item: (checkbutton, int_var)}
        self.count = 0
        self.dict_keys = ["Item1", "Item2", "Item3", "Item4"]
        self.selected = {}

        # 创建复选框
        for item in self.dict_keys:
            self.create_check_box(item)

        self.entry_btn = ttk.Button(self, text="Add", command=self.add_to_list)
        self.entry_btn.grid(row=0, column=1)

        self.entry_btn2 = ttk.Button(self, text="Clear", command=self.clear_list)
        self.entry_btn2.grid(row=0, column=2)

        self.entry_btn3 = ttk.Button(self, text="Continue", command=self._continue)
        self.entry_btn3.grid(row=0, column=3)

    def create_check_box(self, item):
        int_var = tk.IntVar(value=0)  # 默认未选中
        checkbutton = ttk.Checkbutton(self, text=item, variable=int_var, command=lambda: self.check_state(item))
        checkbutton.grid(row=self.count + 1, column=0, sticky='w')
        self.checkboxes[item] = (checkbutton, int_var)  # 同时存储控件与变量
        self.count += 1

    def check_state(self, item):
        _, var = self.checkboxes[item]
        state = var.get()
        print(f"复选框 '{item}' 状态: {state}")

    def add_to_list(self, _event=None):
        selected_items = [item for item, (_, var) in self.checkboxes.items() if var.get() == 1]
        print(f"选中项: {selected_items}")

    def clear_list(self):
        for _, var in self.checkboxes.values():
            var.set(0)

    def _continue(self):
        if messagebox.askyesno(title='确认继续?', message='确定要继续吗?'):
            # 保存选中内容
            self.selected = {key: 'Selected' for key, (_, value) in self.checkboxes.items() if value.get() == 1}
            print(self.selected)
            # 销毁所有复选框控件
            for checkbutton, _ in self.checkboxes.values():
                checkbutton.destroy()
            # 清空复选框字典与计数
            self.checkboxes.clear()
            self.count = 0
            
if __name__ == "__main__":
    main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 06:55:55