Creating StringVar Variables in a Loop for Tkinter Entry Widgets

前端 未结 2 1970
盖世英雄少女心
盖世英雄少女心 2021-01-22 10:11

I have a small script that generates a random number of entry widgets. Each one needs a StringVar() so I can assign text to the widget. How can I create these as part of the loo

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-22 10:53

    The direct answer to your question is to use a list or dictionary to store each instance of StringVar.

    For example:

    vars = []
    for i in range(height):
        var = StringVar()
        vars.append(var)
        b = Entry(..., textvariable=var)
    

    However, you don't need to use StringVar with entry widgets. StringVar is good if you want two widgets to share the same variable, or if you're doing traces on the variable, but otherwise they add overhead with no real benefit.

    entries = []
    for i in range(height):
        entry = Entry(root, width=100)
        entries.append(entry)
    

    You can insert or delete data with the methods insert and delete, and get the value with get:

    for i in range(height):
        value = entries[i].get()
        print "value of entry %s is %s" % (i, value)
    

提交回复
热议问题