【发布时间】:2020-03-27 14:30:47
【问题描述】:
我正在重组这个问题:我觉得最初的问题很啰嗦,对其他人没有特别的帮助。
我有一个直接运行的主应用程序(运行为__main__)。 我有一个只希望用作导入的模块(simple_module.py)。 我意识到如果需要(通过 if__name__)我可以独立运行它,并将其包含在模块代码中,仅用于演示。
当用户按下 main.py 的“开始”按钮时,它应该会打开一个新的顶层窗口,其中包含来自 simple_module 的所有类和小部件,它们都在一个名为 Page 的类中。 (同时主应用程序窗口保持打开状态。)
我希望每次按下按钮时都重新导入(或等效)模块。当按下模块“关闭”按钮或 X 时,我希望它关闭该窗口。 main.py 的窗口在整个过程中保持打开状态,按下按钮需要重新打开该模块窗口,就像循环一样无限。
我添加了 if name == 'main' 只是为了强调我了解它的作用(通常在我的所有 main.py 应用程序中)以及为什么我仍然无法得到我想要的结果。据我所见,它并没有改变任何东西,我现在只导入类,但仍然无法识别“新”。这与前面的示例中的问题相同。
我有 main.py
import tkinter as tk
# audio module works as expected
import audio_module as am
# I want this window to open and close on command
import simple_module as sm
class GUI(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
#self.new = tk.Toplevel(self) # auto loads a second, unwanted window
self.session_counter = 0
self.start_btn = tk.Button(root, text="start", command=self.start)
self.start_btn.grid(row=4,column=0,sticky="nsew",pady=30, padx=30, ipady=18)
def start(self):
am.spell() # these audio imports work like a charm, every btn press - single functions call OK
self.session_counter += 1
print(self.session_counter)
#import simple_module - if used here, my usual 'illegal' import style (works great, once only,
# unless in same script as __main__ in which case all re-imports work fine)
# Import attempts
#import simple_module as sm
#page = Page(new) # Page not defined
#sm.Page() #missing parent arg (new)
# error: 'new' not defined
#sm.Page(new)
if __name__ == '__main__':
print('running as __main__')
root = tk.Tk()
#sm.Page = tk.Toplevel(new) # a desperate attempt NO
#page = sm.Page(tk.TopLevel) NO
# qualify and USE module here! sm is not required if you use 'from simple_module import Page' !!
page = sm.Page(root)
#page.pack(fill='both', expand=True)
page.grid(row=0,column=0,sticky='nsew')
main = GUI(root)
root.mainloop()
最后,我们有了 simple_module.py:
import tkinter as tk
import audio_module as am
# this module works exactly as expected IF run directly...
class Page(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
# super().__init__(*args, **kwargs)
self.back_btn = tk.Button(parent, text="close", command=self.back)
self.back_btn.grid(row=4,column=0,sticky="nsew",pady=30, padx=30, ipady=18)
def back(self):
am.click()
# close this page BUT have it ready to re-open IF user re-presses button.
new.destroy()
if __name__ == "__main__":
print('running as __main__ directly')
new = tk.Tk()
#new = tk.Toplevel() # this loads an unwanted additional blank window. IF run directly.
page = Page(new)
# the missing line to self contain module!
#page.pack(fill='both', expand=True)
page.grid(row=0,column=0,sticky='nsew')
new.mainloop()
else:
print('running as import with __name__ ==',__name__)
感谢您的耐心和回复。我重新研究了您提供链接的 if main 指南,它再次确认了我已经相信我知道的内容。当我只想打开一个框架并在它们之间切换时,这是一个有用的示例,但在这种情况下,我希望主窗口在调用模块窗口时保持打开状态。
【问题讨论】:
标签: python-3.x oop tkinter