0

I am new in python and a need to have in my solution multiple labels. My solution was below. Somebody has a better solution for this? I need 20 labels.

            if pos_x == 1:
                lb1 = Label(janela, text=data[rabo], font="arial 18")
                lb1.grid(row=pos_x, column=pos_y, padx=2, pady=2)
            if pos_x == 2:
                lb2 = Label(janela, text=data[rabo], font="arial 18")
                lb2.grid(row=pos_x, column=pos_y, padx=2, pady=2)
            if pos_x == 3:
                lb3 = Label(janela, text=data[rabo], font="arial 18")
                lb3.grid(row=pos_x, column=pos_y, padx=2, pady=2)
            if pos_x == 4:
                lb4 = Label(janela, text=data[rabo], font="arial 18")
                lb4.grid(row=pos_x, column=pos_y, padx=2, pady=2)
            if pos_x == 5:
                lb5 = Label(janela, text=data[rabo], font="arial 18")
                lb5.grid(row=pos_x, column=Pos_y, padx=2, pady=2)
  • 1
    Use a loop and a list. – Matthias Nov 20 '19 at 09:11
  • Why are you giving all the labels different variable names?, you should also be using `elif` but really theres no need for any of these if statements – Sayse Nov 20 '19 at 09:12
  • 3
    Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – Sayse Nov 20 '19 at 09:14

2 Answers2

1

Using lb1,...,lb5 (up to lb20) is looking strange to me. They are almost (?) identical, so I would suggest to use a list:

lb = [None] * number_of_lb  # make array of 20 None
...
lb[pos_x] = Label(..)
lb[pos_x].grid = ...

Later you can access them as lb[0], lb[1], etc.

George Shuklin
  • 6,952
  • 10
  • 39
  • 80
0

use

if pos_x == i:
    lb[i] = Label(janela, text=data[rabo], font="arial 18")              
    lb[i].grid(row=pos_x, column=pos_y, padx=2, pady=2)
ArunJose
  • 1,999
  • 1
  • 10
  • 33