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

Tkinter中如何点击按钮一键关闭两个窗口?

解决方案

要实现点击save_drink函数内的关闭按钮时,同时关闭自身生成的newtop窗口和add_drink生成的top窗口,核心是让save_drink能获取到add_drink创建的top窗口对象,具体修改如下:

修改步骤

  1. 传递窗口对象:在add_drink中调用save_drink时,把生成的top窗口作为参数一起传入
  2. 自定义关闭逻辑:在save_drink中定义一个同时销毁两个窗口的函数,绑定给关闭按钮

修改后的完整代码

def save_drink(added_drink, top):
    drinks_list = []
    newtop = Toplevel(root)
    newtop.geometry("200x200")
    newtop.title("Drink Added")
    label = Label(newtop, text= "{} Added".format((added_drink.get())), font=('Mistral 10')).pack()
    
    # 自定义同时关闭两个窗口的函数
    def close_both_windows():
        newtop.destroy()
        top.destroy()
    
    close_button = Button(newtop, text="Close", command=close_both_windows)
    close_button.pack()
    drinks_list.append(added_drink.get())


def add_drink():
    top = Toplevel(root)
    top.geometry("750x250")
    top.title("Record Drink")
    label = Label(top, text= "What drink did you have?", font=('Mistral 18')).pack()
    added_drink = Entry(top, font=6)
    added_drink.pack()
    # 调用save_drink时传入top窗口对象
    added_drink_button = Button(top, text='Add Drink', font=3,
                                command=lambda: save_drink(added_drink, top)).pack()

补充说明

  • 若需要drinks_list在多次调用中保留数据,不要将其定义为save_drink的局部变量,可改为全局变量或类属性
  • lambda表达式在这里的作用是传递额外参数(top窗口),避免按钮绑定命令时直接执行函数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:35:32