Question

I basically have this loop and I am trying to make it so that each of the labels in the GUI has a specific name so I can change them individually. I would like it to be cardlabelxy where x is the row and y is the column but I can'f figure out how to get it to work. Here is what I have:

for i in range(2):
    for j in range(6):
        (cardlabel+'i'+'j') = CardLabel(root)
        (cardlabel+'i'+'j').grid(row=i, column=j)
        (cardlabel+'i'+'j').configure(image=CardLabel.blank_image)

Can anyone help me with the syntax? the loop works fine if i just have

for i in range(2):
    for j in range(6):
        cardlabel = CardLabel(root)
        cardlabel.grid(row=i, column=j)
        cardlabel.configure(image=CardLabel.blank_image)

but then they are all called cardlabel which I don't want.

Was it helpful?

Solution

Don't build dynamic variables; keep your data out of your variables. Build a list or dictionary instead.

With a dictionary, for example, it'd be:

card_labels = {}

for i in range(2):
    for j in range(6):
        label = CardLabel(root)
        label.grid(row=i, column=j)
        label.configure(image=CardLabel.blank_image)
        card_labels[i, j] = label

This stores the labels keyed on the (i, j) tuple in the card_labels dictionary.

OTHER TIPS

You could try using dictionary, like this:

cardlabels = {}

for i in range(2):
    for j in range(6):
        label = str(i)+'.'+str(j)
        cardlabels[label] = CardLabel(root)
        cardlabels[label].grid(row=i, column=j)
        cardlabels[label].configure(image=CardLabel.blank_image)

Now they will be labeled cardlabels['1.1'], cardlabels['1.2']..

While I definitely recommend using either a dictionary or list solution, if you have your heart set on using variables, something like this should do the trick.

for i in range(2):
    for j in range(6):
        vars()['cardlabel%d%d' % (i,j)] = CardLabel(root)
        vars()['cardlabel%d%d' % (i,j)].grid(row=i, column=j)
        vars()['cardlabel%d%d' % (i,j)].configure(image=CardLabel.blank_image)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top