使用 Tkinter 获取动态生成的 Entry 字段的值 [英] Getting values of dynamically generated Entry fields using Tkinter

查看:36
本文介绍了使用 Tkinter 获取动态生成的 Entry 字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个属性列表,例如成本、价格、isObsolete 等,我想动态地生成一个标签,下面有一个条目字段,供用户插入正确的值.

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.

似乎最好的方法是将属性与字典中的值存储起来,并在 Entry 字段更新时更新此字典.

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.

我尝试在分配给我的输入字段的 StringVar 上使用 trace_variable 函数,但是当我在该字段中输入内容(作为测试)或在类上运行一个函数以获取字典的键和值:

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?

推荐答案

StringVar 保存在数组中

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()

这篇关于使用 Tkinter 获取动态生成的 Entry 字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆