2016-01-23 63 views
-1

有問題的部分是我要求用戶輸入一個類, 我希望使用從另一個類中的該條目獲得的值, 但是,無論如何,此代碼總是給我0已進入。 我認爲這可能是因爲當另一個類被執行時,存儲在前一個類的入口中的值消失。但我不知道如何去解決它。 任何編碼大師能幫我一點點嗎?如何將Tkinter中的某個條目的值傳遞給另一個類?

...... 

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

此問題是http://stackoverflow.com/q/32212408/7432的副本。 –

回答

1

你可以做NumOfVertices一個全局變量,並調用NumOfVertices.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) 

另外,避免了全局變量,你可以做NumOfVerticesPageOne實例的屬性 。

然後,當您實例化PageTwo時,還要傳遞PageOne的實例,以便查找其NumOfVertices屬性。

class PageOne(tk.Frame): 

    def __init__(self, parent, controller): 
     tk.Frame.__init__(self, parent) 
     ... 
     self.NumOfVertices = tk.IntVar() 
     NumOfVerticesEntry = tk.Entry(self, textvariable=self.NumOfVertices) 

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


class PageTwo(tk.Frame): 

    def __init__(self, parent, controller, pageone): 
     tk.Frame.__init__(self, parent) 
     VertexNumber = pageone.NumOfVertices.get() 
     label = tk.Label(self, text=VertexNumber) 
+0

第二種方法會導致有4個參數但預期只有3個錯誤的錯誤,有沒有解決這個問題的方法? –

+0

我想我定義了前面的「def __init __(self,* args,** kwargs):」在代碼的基礎上, –

+0

當你實例化'PageTwo'時,一定要將它傳遞給'PageOne'的實例。 – unutbu