2015-11-19 82 views
0

我正在嘗試將老式順序Tkinter代碼放入類結構代碼中。如何從課堂上獲得Tkinter Var的價值?

因此,讓我們考慮這個例子:

import Tkinter as Tk 

def StartProcess(): 
    print Text_1_Var.get(), Text_2_Var.get(), Text_3_Var.get() 

if __name__ == '__main__': 
    MainFrame = Tk.Tk() 

    Tk.Button(MainFrame , text = "Start",command=StartProcess).grid(column=2, row=0) 
    Tk.Label(MainFrame , text = "1").grid(column=1, row=1) 
    Text_1_Var = Tk.StringVar() 
    Text_1 = Tk.Entry(MainFrame , width=40, textvariable = Text_1_Var).grid(column=2, row=1) 
    Tk.Label(MainFrame , text = "2").grid(column=1, row=2) 
    Text_2_Var = Tk.StringVar() 
    Text_2 = Tk.Entry(MainFrame , width=40, textvariable = Text_2_Var).grid(column=2, row=2) 
    Tk.Label(MainFrame , text = "3").grid(column=1, row=3) 
    Text_3_Var = Tk.StringVar() 
    Text_3 = Tk.Entry(MainFrame , width=40, textvariable = Text_3_Var).grid(column=2, row=3) 
    # etc 

    MainFrame.mainloop() 

在按 「開始」,它顯示輸入1的值3

現在我重新編寫它如下:

import Tkinter as Tk 

def StartProcess(): 
    print "???" 

class NewEntry(Tk.Frame): 
    def __init__(self,master=None,idnumber=None): 
     Tk.Frame.__init__(self,master) 
     self.pack(side=Tk.TOP) 
     self.CreateWidgets(idnumber) 
    def CreateWidgets(self,idnumber): 
     Tk.Label(master=self, text = idnumber).grid(column=1, row=0) 
     self.Text_Var = Tk.StringVar()   
     self.Text = Tk.Entry(master=self, width=40, textvariable = self.Text_Var).grid(column=2, row=0) 

if __name__ == '__main__': 
    MainFrame = Tk.Tk() 

    Tk.Button(master=MainFrame,text="Start", command=StartProcess).pack() 
    for i in range (1, 4): # or more 
     NewEntry(master=MainFrame,idnumber=str(i)) 

    MainFrame.mainloop() 

GUI都是相同的。我想獲得相同的結果,但我不知道我的函數StartProcess應該在哪裏發生,以及如何提取每個self.Text_Var實例的值。

回答

1

僅僅創建一個NewEntry對象是不夠的;您需要保存對它們的引用,以便稍後可以訪問它們(例如,從StartProcess)。

entries = [] 
for i in range (1, 4): # or more 
    e = NewEntry(master=MainFrame,idnumber=str(i)) 
    entries.append(e) 
# Or more simply, 
# entries = [NewEntry(master=MainFrame, idnumber=str(i)) for i in range(1,4)] 

然後,StartProcess變得像

def StartProcess(): 
    strings = [x.Text_Var.get() for x in entries] 
    print " ".join(strings) 
+0

輕鬆!我不認爲我們可以做Tkinter物品清單。這非常方便。謝謝。 – Syrius