当我打开下一个窗口时,试图让我的GUI窗口自动退出



单击下一个窗口按钮时,如何自动取消第一个窗口?

示例代码:

from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("GUI practice")
def open():
top = Toplevel()  # new window
top.title("Kokomi")
labels = Label(top, text="This one automatically close when i click the next window").pack()
button2 = Button(top,text="Close window", command=top.destroy).pack()
button3 = Button(top,text="Next window", command=open2).pack()
def open2():
top = Toplevel()  # new window
top.title("Guide")
labels = Label(top, text="end").pack()
button2 = Button(top, text="Close window", command=top.destroy).pack()  # destroy to quit things
button = Button(root, text="Open(No need to close this)", command=open).pack()

root.mainloop()

[Click open][1]
[Click Next window and after that this windows should disappear and continue to the 3rd picture][2]
[The 2nd picture goes disappear when i click the next window][3]
[1]: https://i.stack.imgur.com/plS1T.png
[2]: https://i.stack.imgur.com/EFW76.png
[3]: https://i.stack.imgur.com/xSZCp.png

对于使用两个函数和两个窗口的特定情况,您只需将Toplevel小部件重命名为不同的名称,然后全局化一个小部件,然后从另一个函数访问它,并在显示新窗口之前销毁它。

def open():
global top
top = Toplevel()  # new window
top.title("Kokomi")
Label(top, text="This one automatically close when i click the next window").pack()
Button(top, text="Close window", command=top.destroy).pack()
Button(top, text="Next window", command=open2).pack()
def open2():
top.destroy() # Destroy previously open window
top1 = Toplevel()  # new window
top1.title("Guide")
Label(top1, text="end").pack()
Button(top1, text="Close window", command=top1.destroy).pack()  # destroy to quit things

如果你注意到了,我删除了按钮和标签的变量名,因为它们的值是None,读取Tkinter:AttributeError:NoneType对象没有属性<属性名称>。

当您希望使用更多的功能和窗口时,您必须手动执行所有功能的此过程。当然,除非有一种更好、更干净的方法可以使用类和框架来设计你的应用程序。

或者您也可以从一个按钮调用两个函数,这种方法将摆脱全球化和重命名,可能比上面提到的解决方案好一点:

def open():
top = Toplevel()  # new window
top.title("Kokomi")
Label(top, text="This one automatically close when i click the next window").pack()
Button(top, text="Close window", command=top.destroy).pack()
Button(top, text="Next window", command=lambda: [top.destroy(),open2()]).pack()
def open2():
top = Toplevel()  # new window
top.title("Guide")
Label(top, text="end").pack()
Button(top, text="Close window", command=top.destroy).pack()  # destroy to quit things

最新更新