2016-07-15 82 views
0

如何在下面的代碼中引用小部件值。在這裏我已經通過調用應用程序類中的方法爲不同的框架添加小部件。接下來,我想訪問所有小部件中的值(該用戶在同一時間。但我無法弄清楚,我應該如何引用他們,並訪問它們的值進入)所有的幀!在tkinter中獲取小部件值

class myapp(): 
    def __init__(self,parent): 
     self.parent=parent 
     self.container=Frame(self.parent) 
     self.container.pack() 

     self.tab1=Button(self.container,text='tab1',command=self.tab1Click) 
     self.tab2=Button(self.container,text='tab*emphasized text*2',command=self.tab2Click) 
     self.tab1.pack() 
     self.tab2.pack() 
    def tab1Click(self): 
     top=Toplevel() 
     self.container1=Frame(top) 

     self.add_widget1(self.container1)#self.add_widgeti(parent) is a method in myapp() class to add a widget to a frame 
     self.add_widget2(self.container1) 
     self.add_widget3(self.container1) 

     self.container1.pack() 

    def tab2Click(self): 
     top=Toplevel() 
     self.container2=Frame(top) 

     self.add_widget2(self.container2) 
     self.add_widget4(self.container2) 
     self.add_widget5(self.container2) 

     self.container2.pack() 

    def write(self): 
     #here I want to write the values contained in the widgets in both frames in a file,but I am not able to figure out how do I refer to them and access their values. 

任何幫助將不勝感激。提前感謝。

回答

1

在其中用戶可以寫有一個get方法,它返回其內容的窗口小部件。但是,爲了做到這一點,你需要你的widget存儲在例如一個類變量。

編輯:我誤會了這個問題,我沒有意識到add_widget函數將被調用不同的容器爲同一個實例。保留所有創建的Widget跟蹤一個方法是創建一個小部件列表:

  • 添加self.widgets = []__init__

  • 定義add_widget方式類似:

def add_widget(self, container): 
     self.widgets.append(Entry(container, text="enter text here")) 
     self.widgets[-1].pack() 

然後獲取文本確認E在所有小工具用戶(寫函數內)d:

texts = [] 
for widget in self.widgets: 
    texts.append(widget.get()) 
+0

:可是我怎麼在參考write()方法來WIDGET2,因爲它是在兩個格container1和container2.I想知道,如果有一些在他們的父母而言指的小部件的方式(類似container.widget2 ......但我無法找到它)。請幫助! – cooltogo

+0

Thanks.It工作! – cooltogo