Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tkinter create labels and entrys dynamically

Tags:

python

tkinter

I want to create a simple GUI where I can enter some values. A label before and at the and an button to start the script.

I was using something like this:

w = Label(master, text="weight:")
w.grid(sticky=E)
w = Label(root, text="bodyfathydrationmuscle:bones")
w.grid(sticky=E)
w = Label(root, text="hydration:")
w.grid(sticky=E)

its ok but i want to do it dynamic. also when i would use w for all the entrys i only could cast w.get once. but i need all my data ;-)

i was thinking of:

  def create_widgets(self):
    L=["weight","bodyfat","hydration","muscle","bones"]
    LV=[]
    for index in range(len(L)):
        print(index)
        print(L[index])
        ("Entry"+L[index])= Entry(root)
        ("Entry"+L[index]).grid(sticky=E)
        ("Label"+L[index])=Label(root, text=L[index])
        ("Label"+L[index]).grid(row=index, column=1)

To call later:

var_weight=Entryweight.get()
var_bodyfat=Entrybodyfat.get()

and so on. how can i make it work?

like image 888
jason106 Avatar asked Mar 29 '26 02:03

jason106


1 Answers

Your program suggests that Entrybodyfat and the other variables should be generated on the fly, but you don't want to do that.

The normal approach is to store the entries and labels in a list or a map:

from Tkinter import *

root = Tk()

names = ["weight", "bodyfat", "hydration", "muscle", "bones"]
entry = {}
label = {}

i = 0
for name in names:
    e = Entry(root)
    e.grid(sticky=E)
    entry[name] = e

    lb = Label(root, text=name)
    lb.grid(row=i, column=1)
    label[name] = lb
    i += 1

def print_all_entries():
    for name in names:
        print entry[name].get()

b = Button(root, text="Print all", command=print_all_entries)
b.grid(sticky=S)

mainloop()

The value of the bodyfat entry is then entry["bodyfat"].get().

like image 173
antonakos Avatar answered Apr 01 '26 09:04

antonakos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!