2016-07-15 83 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