Getting values of dynamically generated Entry fields using Tkinter

依然范特西╮ 提交于 2021-01-28 07:12:37

问题


I've got a list of attributes such as cost, price, isObsolete etc. which I would like to dynamically generate as a label with an Entry field underneath, for the user to insert the correct value into.

It seems the best way to do this is to store the attributes against the values in a dictionary, and update this dictionary whenever the Entry field is updated.

I've tried used the trace_variable function on the StringVar assigned to my entry field, but it doesn't seem to when I type into the field (as a test) or when I run a function on the class to get the keys and values of the dictionary:

from Tkinter import *
import ttk

t = ['cost','price','isObsolete']

root = Tk()

rowAcc = 1
colAcc = 0

d = {}

for item in t:
    newValue = StringVar()

    def callback(*args):
        print args[0] + " variable changed to " + newValue.get()
        d[item] = newValue.get()

    newValue.trace_variable("w", callback)

    ttk.Label(root, text=item).grid(column=colAcc, row=rowAcc, sticky=(N, W))

    reqEntry = ttk.Entry(root, textvariable=newValue, width=19)
    reqEntry.grid(column=colAcc, row=rowAcc + 1, sticky=(N, W), pady=3, padx=1)

    colAcc += 1

def printDict():
    for key in d:
        print key, d[key]

root.mainloop()

Is there a way of tweaking this to achieve my result, or is there a better solution altogether to getting the values of dynamically generated entry fields?


回答1:


Save StringVar in array

from Tkinter import *

master = Tk()

frame = Frame(master)
frame.pack()

s_vars = []

for i in range(5):
    s_vars.append( StringVar() )

    def onChange(a ,b, c, s_var):
        print a, "changed to", s_var.get()

    s_vars[i].trace('w', lambda a, b, c, x=i: onChange(a, b, c, s_vars[x]) )

    en = Entry(frame, textvariable=s_vars[i])
    en.pack()

    s_vars[i].set( str(i) )

mainloop()


来源:https://stackoverflow.com/questions/24282331/getting-values-of-dynamically-generated-entry-fields-using-tkinter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!