如何将类中的条目中的值传递给Tkinter中的另一个类?

时间:2016-01-23 17:53:42

标签: python oop tkinter

出现问题的部分是我要求用户输入一个类, 我希望在另一个类中使用从该条目获得的值, 但是,无论我输入什么,这段代码总是给我0。 我认为这可能是因为当执行另一个类时,存储在前一个类的条目中的值会消失。但我不知道如何绕过它。 任何编码大师都可以帮我一点吗?

......

class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        BackButton = tk.Button(self, text="Back",font=TNR24,command=lambda: controller.show_frame(MainPage))
        PrintButton = tk.Button(self, text="Print it", command=self.print_message)
        ExitButton = tk.Button(self,text="EXIT",command=exit_window)
        ProceedButton=tk.Button(self, text="Proceed", command=lambda: controller.show_frame(PageTwo))
        self.NumOfVertices= tk.IntVar()
        global VertexNumber
        VertexNumber=self.NumOfVertices.get()
        NumOfVerticesEntry=tk.Entry(self,textvariable=self.NumOfVertices)
        ProceedButton.pack()
        BackButton.pack()
        ExitButton.place(x=1240, y=670, width=40, height=30)
        PrintButton.pack()
        NumOfVerticesEntry.pack()

    def print_message(self):
        print self.NumOfVertices.get()


class PageTwo(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)

        lable=tk.Label(self,text=VertexNumber)

......

代码很长,所以我只接受了需要帮助的部分。 VertexNumber是我想要在Pagetwo类中存储和使用的变量。 但无论我输入什么,它总是变成0。 有没有办法在用户输入后立即永久存储该变量?

1 个答案:

答案 0 :(得分:1)

您可以将var contact = [{ 'name': "Peter Parker" }]; 设为全局变量,然后致电NumOfVerticesNumOfVertices.get()中获取PageTwo当前值

IntVar

或者,要避免全局变量,可以使NumOfVertices = tk.IntVar() class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) ... NumOfVerticesEntry = tk.Entry(self, textvariable=NumOfVertices) def print_message(self): print NumOfVertices.get() class PageTwo(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) VertexNumber = NumOfVertices.get() label = tk.Label(self, text=VertexNumber) 成为一个 NumOfVertices实例的属性。

然后,当您实例化PageOne时,也会传递PageTwo的实例,以便查找其PageOne属性。

NumOfVertices
相关问题