在tkinter中获取窗口小部件值

时间:2016-07-15 20:38:40

标签: python tkinter

如何在下面的代码中引用窗口小部件值。这里我通过在app类中为不同的frame调用方法添加了小部件。接下来,我想访问所有小部件中的值(用户输入的小部件)但是我无法弄清楚如何引用它们并访问它们的值!

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 个答案:

答案 0 :(得分:1)

用户可以编写的小部件具有返回其内容的get方法。但是为了做到这一点,您需要将窗口小部件存储在类变量中,例如。

编辑:我误解了这个问题,但我没有意识到同一实例的不同容器会调用add_widget函数。跟踪所有创建的小部件的一种方法是创建小部件列表:

  • self.widgets = []

  • 中添加__init__
  • 定义add_widget方法:

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

然后获取用户在所有小部件(写入函数内)中输入的文本:

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