从单独的函数

时间:2018-04-21 16:21:45

标签: python tkinter

如果标题有点宽泛,请道歉。

我正在创建一个包含多个页面的Tkinter应用程序,我正在使用this段代码来执行此操作。

每个页面都是一个框架,通过调用“show_frame”函数来提升框架。使用按钮在页面之间切换没有问题,但是如果满足条件,我想运行某个功能并更改页面。

以下是一个例子:

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        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, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Go to Page Two",
                            command=lambda: controller.show_frame("PageTwo"))
        button1.pack()
        button2.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()

def doSomething():
    ...
    if x == y:
        "RAISE PAGE ONE"

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

如您所见,doSomething函数不在任何类中。我如何从这个功能中提升PageOne。

1 个答案:

答案 0 :(得分:0)

最简单的答案是使 doSomething ()成为 SampleApp 的方法。然后,您可以访问方法 show_frame 。但是,你的问题似乎暗示这不是一种选择。

如果不这样做,我建议将 app 传递给该函数,然后调用 app.show_frame(“PageName”)

如果您不想将指向 app 的指针作为参数传递,那么您可以传递 doSomething 函数 app.show_frame as foo ,然后在希望显示页面时调用 foo (“PageName”)。

E.g。

def doSomething(foo):
    '''some code'''
    foo("page name")

doSomething(app.show_frame)