迭代地向Tkinter表单添加标签

时间:2015-06-29 19:32:55

标签: python python-2.7 tkinter

我试图通过循环遍历列表来迭代地将字段添加到Tkinter表单。生成的表单没有错误,但标签不存在。这里发生了什么?

from Tkinter import *
class User_Input:

def __init__(self, parent):
    fields = ['Text Box 1', 'Text Box 2', 'Text Box 3']
    GUIFrame =Frame(parent, width=300, height=200)
    GUIFrame.pack(expand=False, anchor=CENTER)
    field_index = 10
    for field in fields:
        self.field = Entry() #possibly make this Entry(GUIFrame)
        self.field.place(x=65, y = field_index)
        field_index += 25

    field_index = 10
    for field in fields:
        self.field = Label()
        self.field.place(x=0, y = field_index)
        field_index += 25

    self.Button2 = Button(parent, text='Done', command= parent.quit)
    self.Button2.place(x=150, y=field_index)

root = Tk()
MainFrame =User_Input(root)

root.mainloop()

2 个答案:

答案 0 :(得分:0)

首先,你在循环中覆盖你的self.field。只有最后一个条目不会被垃圾收集。添加列表属性self.fields并将每个条目附加到它。并为您的参赛作品提供一个家长。

答案 1 :(得分:0)

text的{​​{1}}属性看起来并没有真正做任何事情。尝试将字符串显式插入窗口小部件。

Entry

现在您的参赛作品的默认值为"文本框1"和#34;文本框2"分别

如果您希望文字之外,我认为没有明确创建标签并将其放在旁边的任何方式可以做到这一点条目。但是你可以通过创建一个为你创建两个小部件的自定义类来减少你的簿记。

    for field in fields:
        self.field = Entry() #possibly make this Entry(GUIFrame)
        self.field.insert(END, field)
        self.field.place(x=65, y = field_index)
        field_index += 25

(虽然这有点使条目上的属性/方法访问变得复杂,但现在你需要做from Tkinter import * class LabeledEntry(Frame): def __init__(self, parent, *args, **kargs): text = kargs.pop("text") Frame.__init__(self, parent) self.label = Label(self, text=text) self.label.grid(column=0,row=0) self.entry = Entry(self, *args, **kargs) self.entry.grid(column=1,row=0) class User_Input: def __init__(self, parent): fields = ['Text Box 1', 'Text Box 2'] GUIFrame =Frame(parent, width=300, height=200) GUIFrame.pack(expand=False, anchor=CENTER) field_index = 10 for field in fields: self.field = LabeledEntry(GUIFrame, text=field) self.field.place(x=65, y = field_index) field_index += 25 self.Button2 = Button(parent, text='exit', command= parent.quit) self.Button2.place(x=160, y=60) root = Tk() MainFrame =User_Input(root) root.mainloop() 而不是self.field.entry.insert(...)。但是你总是可以定义一个自定义的self.field.insert(...)方法insert,如果您感到倾向,则会将其参数传递给LabeledEntry。)

更新以回复问题编辑:或只指定标签的self.entry.insert属性。

text
相关问题