简体   繁体   English

如果tk.Toplevel在其他文件中,如何关闭窗口

[英]How to close a window if tk.Toplevel is in a different file

how do I close my current window if I can't see the tk.Toplevel(root) from the method I am in? 如果我所使用的方法看不到tk.Toplevel(root),如何关闭当前窗口?

Here a small example of what i mean: 这是我的意思的一个小例子:

file1.py: file1.py:

import Tkinter as tk
import file2
class ExampleMain:
    def __init__(self, root):
        self.mainFrame = tk.Frame(root)
        ...
        tk.Button(self.mainFrame, command=self.button_pressed)
        ...

    def button_pressed(self):
        self.whatever = tk.Toplevel(root)
        self.app = file2.ExampleNotMain(self.whatever)

if __name__ == '__main__':
    root = tk.Tk()
    app = ExampleMain(root)
    root.mainloop()

file2.py: file2.py:

import tkinter as tk
class ExampleNotMain:
    def __init__(self, root):
        self.frame = tk.Frame(root)
        ...
        tk.Button(self.frame, command=self.close_window)
        ...

    def close_window(self):
        =>  missing_command_here

In this example I would like to close the second window created (and keep the first). 在此示例中,我想关闭创建的第二个窗口(并保留第一个窗口)。

If all the code is in one file something like 如果所有代码都在一个文件中,则类似

self.whatever.destroy()

would do it. 会做到的。 My problem is I can't see the object from the first file with the command being in the second file. 我的问题是我看不到第一个文件中的对象,而命令位于第二个文件中。

I found something like 我发现类似

execfile("file2.py") 

but I don't like that solution. 但我不喜欢这种解决方案。

Is there a better way to solve my problem? 有没有更好的方法来解决我的问题?

I would realy apriciate your help. 我真的很感谢您的帮助。 Thanks in advance. 提前致谢。

When you create ExampleNotMain, you pass the 2nd Toplevel self.whatever. 创建ExampleNotMain时,您将传递第二个顶级self.what。 In ExampleNotMain.__init__ , it gets bound to root . ExampleNotMain.__init__ ,它绑定到root ( master or parent would be a better parameter name). masterparent会是一个更好的参数名称)。 In __init__ , add self.top = root (or whatever you call the passed-in toplevel). In __init__ ,添加self.top = root (or whatever you call the passed-in toplevel). In (or whatever you call the passed-in toplevel). In close_window , add self.top.destroy()`. (or whatever you call the passed-in toplevel). In close_window中, add self.top.destroy()`。

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

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