使用tkinter在按钮单击时将变量传递给其他帧

时间:2017-03-03 15:45:36

标签: python tkinter

我很难用tkinter理解面向对象编程..

对于此示例,我希望用户输入一些数据,然后在新框架中显示它。但问题是输入似乎在按下“检查”按钮之前通过。

如何在按下“检查”按钮之前等待将数据传递给PageOne?

这是我到目前为止编写的代码(在一些示例代码的帮助下):

import tkinter as tk


class Window(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)  # master
        container.grid()

        self.frames = {}

        for F in (StartPage, PageOne):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

    def get_page(self, page_class):
        return self.frames[page_class]


class StartPage(tk.Frame):  # inherit from tk.Frame
    def __init__(self, parent, controller):
        self.controller = controller
        tk.Frame.__init__(self, parent)

        tk.Label(self, text="Floor Time: ", font='helvetica 30').grid(row=0, sticky="w")
        tk.Label(self, text="MSL: ", font='helvetica 30').grid(row=1, sticky="w")

        self.e1 = tk.Entry(self, width=52)
        self.e2 = tk.Entry(self, width=52)

        self.e1.grid(row=0, column=1, sticky="w", pady=5, ipady=15)
        self.e2.grid(row=1, column=1, sticky="w", pady=5, ipady=15)

        self.e1.insert(0, "<format = hours>")

        button1 = tk.Button(self, text='Check', width="20", height="3", font='helvetica 20', bg="green",
                            command=lambda: controller.show_frame(PageOne))

        button1.grid(row=2, column=0, sticky="w", pady=4, padx=4)

        button2 = tk.Button(self, text='Quit', width="20", height="3", font='helvetica 20', bg="red",
                            command=self.quit)

        button2.grid(row=2, column=1, sticky="e", pady=4, padx=4)


class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        x = self.controller.get_page(StartPage)

        print(x.e1.get())
        print(x.e2.get())


if __name__ == '__main__':
    b = Window()
    b.title("SMD Condition Tool")
    b.mainloop()

1 个答案:

答案 0 :(得分:0)

一种方法是覆盖tkraise方法:

class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.x = self.controller.get_page(StartPage)

    def tkraise(self):
        print(self.x.e1.get())
        print(self.x.e2.get())
        tk.Frame.tkraise(self) # call superclass