简体   繁体   English

Tkinter从顶级破坏根

[英]Tkinter destroy root from Toplevel

I am writing a multi-window GUI program in tkinter. 我正在tkinter中编写一个多窗口GUI程序。 The code shown below is the layout of the main part of my code. 下面显示的代码是我代码主要部分的布局。 The first window works fine but when I get to the second window by calling self.next_win , some things start to go sightly funny. 第一个窗口工作正常,但是当我通过调用self.next_win进入第二个窗口时,有些事情开始变得很有趣。

The main issue is when I go to destroy the GUI: I want there to be a quit button in each window which, when pushed, closes the entire GUI ( root.destroy ). 主要问题是何时销毁GUI:我希望每个窗口中都有一个退出按钮,按下该按钮可关闭整个GUI( root.destroy )。 From the first window this works fine, I call the self.quit method; 从第一个窗口可以正常工作,我调用了self.quit方法。 but when I get to the second window it doesn't work. 但是当我到达第二个窗口时,它不起作用。 I know this is because master in the second window is a Toplevel widget but I'm not sure how to get around this. 我知道这是因为第二个窗口中的masterToplevel小部件,但是我不确定该如何解决。 I don't see how I can call root.destroy from the second window. 我看不到如何从第二个窗口调用root.destroy

How can I fix this? 我怎样才能解决这个问题? A line in the SecondWin.quit method perhaps, or a better code structure which makes the solution trivial (bear in mind I am a beginner so trivialities will have to be explained)? 可能是SecondWin.quit方法中的SecondWin.quit ,或者是使解决方案变得微不足道的更好的代码结构(请记住,我是一个初学者,因此必须解释一些琐碎的事情)? Thanks. 谢谢。

class FirstWin:
    def __init__(self, master):
        self.master = master
        ...

    ...

    def next_win(self):
        self.master.withdraw()
        root2 = Toplevel()
        SecondWin(root2)

    def quit(self):
        self.master.destroy()

class SecondWin:
    def __init__(self, master):
        self.master = master
        ...

    ...

    def quit(self):
        self.master.destroy() # What goes in here?

...

def main():
    root = Tk()
    GUI = FirstWin(root)
    root.mainloop()

if __name__ == '__main__':
    main()

All you need to do is tell SecondWin what the root window is, and it can destroy it. 您需要做的就是告诉SecondWin根窗口是什么,它可以破坏它。

...
    root2 = Toplevel()
    # tell the second window what the master is,
    # and also tell it to be a child of FirstWin.
    SecondWin(self.master, root2)
...

class SecondWin():
    def __init__(self, root, master):
        # root is the root window, master is the parent of this window
        self.root = root
        self.master = master
        <other initialization code here>

    def quit(self):
        self.root.destroy()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM