【问题标题】:Close two windows with one click in tkinter在 tkinter 中一键关闭两个窗口
【发布时间】:2022-09-28 20:47:02
【问题描述】:

我试图在一个函数中获得一个按钮来关闭从另一个函数生成的窗口。这是代码的缩短版本。基本上我希望在save_drink 阶段单击close_button 时关闭从add_drink 生成的顶部窗口。我怎样才能做到这一点?

def save_drink(added_drink):
    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()
    close_button = Button(newtop, text=\"Close\", command=newtop.destroy)
    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()
    added_drink_button = Button(top, text=\'Add Drink\', font=3,
                                command=lambda: save_drink(added_drink)).pack()

    标签: python windows function tkinter


    【解决方案1】:

    您可以尝试将topadd_drink 作为参数传递给save_drink

    added_drink_button = Button(
        top,
        text='Add Drink',
        font=3,
        command=lambda top=top: save_drink(added_drink, top)  # add top to the lambda
    ).pack()
    

    然后修改save_drink 以接受top 参数并相应地处理它 在一个处理关闭Toplevel 小部件的新函数中

    def save_drink(added_drink, top):  # add 'top' here
        drinks_list = []
        newtop = Toplevel(root)
        newtop.geometry("200x200")
        newtop.title("Drink Added")
        label = Label(
            newtop,
            # I suspect there's some extra parentheses around 'format'
            text= "{} Added".format((added_drink.get())), font=('Mistral 10')
        ).pack()
        close_button = Button(
            newtop,
            text="Close",
            # call the 'close' function using a lambda to pass args
            command=lambda t=top, n=newtop: close(t, n)
        )
        close_button.pack()
        drinks_list.append(added_drink.get())
    

    close_button 调用此函数时,将关闭两个窗口

    def close(top, newtop):  # pass both windows as parameters
        top.destroy()
        newtop.destroy()
    

    这应该可行,尽管我怀疑将add_drinksave_drink 函数包装在一个简单的类中可能更容易,这样它们就可以更轻松地共享信息。

    【讨论】:

    • 我尝试了代码,但收到以下错误:'Traceback(最近一次调用最后一次):文件“/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py”,第 1705 行, 在称呼return self.func(*args) TypeError: close() 缺少 2 个必需的位置参数:'top' 和 'newtop''
    • 那是我的错!我已经更新了我的答案,但要点是您需要将 command=close 更改为 command=lambda t=top, n=newtop: close(t, n)
    猜你喜欢
    • 2017-04-16
    • 2018-05-18
    • 2018-01-08
    • 2016-09-23
    • 2017-09-04
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 2021-06-12
    相关资源
    最近更新 更多