在tkinter中关闭窗口的问题

时间:2017-02-03 11:41:25

标签: python python-3.x tkinter

为了让它尽可能短 - 在我的程序中我从Page1开始,当我按下一个按钮我要打开Page2并关闭Page1时,我设法打开Page2但我无法关闭Page1,我尝试过使用{ {1}}但它关闭的不仅仅是页面。我在这里查看了一些关于SO的问题,但是在我的代码中找不到与布局相同的布局,所以我不确定如何将它应用到我的。这是我的第一个.destroy()项目,所以我仍然可以掌握它。

我的代码是;

tkinter

1 个答案:

答案 0 :(得分:2)

如果您销毁root,它会销毁包含的所有小部件,包括Page2。要仅销毁第1页,一种可能性是使页面类继承自tk.Frame,以便它们具有destroy方法:

import tkinter as tk
from tkinter import ttk

class Page1(tk.Frame):
    def __init__(self, master, **kwargs):
        tk.Frame.__init__(self, master, **kwargs)
        self.pack(fill='both', expand=True) # display page 1
        #lots of labels and buttons:
        tk.Label(self, text='Page 1').place(relx=0.5, rely=0.5)
        self.BTNNextPage = ttk.Button(self, text="Proceed", command=self.NextPage)
        self.BTNNextPage.place(x=450, y=420)

    def NextPage(self):
        self.app = Page2(self.master) # create page 2
        self.destroy() # remove page 1

class Page2(tk.Frame):
    def __init__(self, master, **kwargs):
        tk.Frame.__init__(self, master, **kwargs)
        self.pack(fill='both', expand=True) # display page 2
        # create widgets on page 2
        tk.Label(self, text='Page 2').pack()
        tk.Button(self, text='Quit', command=self.master.destroy).pack(side='bottom')

def main():
    widthpixels=690
    heightpixels=500
    root = tk.Tk()
    root.resizable(width=False, height=False)
    root.configure(background='black')
    root.wm_title("Title")
    root.geometry('{}x{}'.format(widthpixels, heightpixels))
    app = Page1(root)
    root.mainloop()

if __name__ == "__main__":
    main()