如何在Tkinter中存储Entry小部件中的值for循环?

时间:2014-04-07 15:22:18

标签: python for-loop tkinter tkinter-entry

这应该是一个非常非常简单的问题。我正在创建一个GUI,其中我有多个条目小部件...大约30个左右都在一列中。不是一个接一个地制作每个盒子,而是用循环生成小部件似乎是个更好的主意。但是,我发现从条目小部件中.get()值非常困难,并将它们转换为浮点数。这是我到目前为止...任何帮助将不胜感激。

class Application(Frame):

def __init__(root,master):
    Frame.__init__(root,master)
    root.grid()
    root.create_widgets()



def calcCR(root):        
    d1 = root.enter.get()
    d1 = float(d1)
    #root.answer.delete(0.0,END)
    a = 'The C/R Alpha is! %lf \n' % (d1)
    root.answer.insert(0.0, a)


def create_widgets(root):
    ### Generate Element List ###
    for i in range(len(elem)):
        Label(root, text=elem[i]).grid(row=i+1, column=0)

    ### Generate entry boxes for element wt% ### 
    for i in range(len(elem)):            
        enter = Entry(root, width = 8)
        enter.grid(row = i+1,column=1)
        enter.insert(0,'0.00')

    root.button = Button(root, text = 'Calculate C/R', command = root.calcCR)
    root.button.grid(row=11, column=2, sticky = W, padx = 10)

    root.answer = Text(root, width = 50, height = 12.5, wrap = WORD)
    root.answer.grid(row=1, column=2, rowspan = 10, sticky = W, padx = 10)    


root = Tk()
root.title('C/R Calculator')
app = Application(root)
root.mainloop()

1 个答案:

答案 0 :(得分:3)

Entry个实例放入列表中。

from tkinter import Tk, Frame, Label, Entry, Button

class App(Frame):
    def __init__(root, master):
        Frame.__init__(root, master)
        root.grid()
        root.create_widgets()

    def get_values(root):
        return [float(entry.get()) for entry in root.entries]

    def calc_CR(root):
        answer = sum(root.get_values()) #Replace with your own calculations
        root.answer.config(text=str(answer))

    def create_widgets(root):
        root.entries = []
        for i in range(20):
            label = Label(root, text=str(i))
            label.grid(row=i, column=0)

            entry = Entry(root, width=8)
            entry.grid(row=i, column=1)
            entry.insert(0, '0.00')
            root.entries.append(entry)

        root.calc_button = Button(root, text='Calculate C/R', command=root.calc_CR)
        root.calc_button.grid(row=20, column=0)

        root.answer = Label(root, text='0')
        root.answer.grid(row=20, column=1)

    def run(root):
        root.mainloop()



root = Tk()
root.title('C/R Calculator')

app = App(root)
app.run()