如何在容器类StartPage中调用MainApp的方法?附实现示例
Python Tkinter 多页面架构下子页面调用主App类方法实现方案
本方案适用于主App类继承tk.Tk、各个子页面为独立tk.Frame子类的容器化多页面开发场景,解决子页面中调用主App类自定义方法的需求。
核心实现逻辑
- 初始化子页面时,主App会将自身实例作为
controller参数传入子页面的构造方法 - 直接通过传入的
controller实例,即可调用主App中定义的所有公开实例方法,不需要通过类名调用
完整示例代码
import tkinter as tk from tkinter.filedialog import askopenfilename # 主App类,继承tk.Tk class App(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} # 注册所有子页面 for F in (StartPage, PageOne): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, rowspan=12, columnspan=6, sticky="nsew") self.show_frame(StartPage) # 页面切换方法 def show_frame(self, c): frame = self.frames[c] frame.tkraise() # 主App自定义方法:打开EEG文件 def open_file(self): filename = askopenfilename(initialdir="C:/000_tmp/", filetypes=(("eeg file", "*.edf"), ("eeg file", "*.EDF"), ('eeg file', '*.fif'), ("all files", "*.*")), title="Choose a file.") return filename # 子页面:首页 class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) # 调用主App的open_file方法的正确写法 EEG_raw = "" if EEG_raw == '': # 直接通过controller实例调用主App方法 selected_file = controller.open_file() # 子页面:页面1 class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) if __name__ == "__main__": app = App() app.mainloop()
常见错误写法说明
不要通过类名直接调用主App的实例方法,如下写法是错误的:
# 错误示例 open_file_if_nonexistent = App.open_file(controller)
这种写法是类方法的调用规则,普通实例方法必须通过已经实例化的controller对象直接调用。
内容的提问来源于stack exchange,提问作者pkanda
相关产品推荐
相关产品推荐

