Creating StringVar Variables in a Loop for Tkinter Entry Widgets

前端 未结 2 1974
盖世英雄少女心
盖世英雄少女心 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:40

    Just store them in a list.

    vars = []
    for i in range(height): #Rows
        for j in range(width): #Columns
            vars.append(StringVar())
            b = Entry(root, text="", width=100, textvariable=vars[-1])
            b.grid(row=i, column=j)
    

    That said, you should probably be storing the Entry widgets themselves in a list, or a 2D list as shown:

    entries = []
    for i in range(height): #Rows
        entries.append([])
        for j in range(width): #Columns
            entries[i].append(Entry(root, text="", width=100))
            entries[i][j].grid(row=i, column=j)
    

    You can then assign text to each widget with the insert() method:

    entries[0][3].insert(0, 'hello')
    

提交回复
热议问题