Reputation: 111
I'm trying to make a for loop that makes labels and entries, using a for loop. Here's the code:
r = 1 #r == row
c = 0 #c == column
n = 1 #n == number
a = 2 #a == checking what iteration
for count in y: #Iterates through y, defined earlier
if a % 2 == 0: #Checks if a is even
Label(edit_recipe_window, text="Ingredient " + str(n)).grid(row=r, column=c)
c += 1
entry_box= Entry(edit_recipe_window)
entry_box.grid(row=r, column=c)
entry_box.insert(0, count)
c = 0
a += 1
else:
Label(edit_recipe_window, text="Quantity and Unit " + str(n)).grid(row=r, column=c)
c += 1
quantity_box = Entry(edit_recipe_window)
quantity_box.grid(row=r, column=c)
quantity_box.insert(0, count)
c = 0
r += 1
a += 1
n += 1
This produces a label of quantity + unit 2, which is not the desired out come.
Upvotes: 0
Views: 6710
Reputation: 7735
If you use print
for debugging, you will see you are putting your widgets on top of eachother on each if-else
pair.
from tkinter import *
edit_recipe_window = Tk()
if 1:
r = 1 #r == row
c = 0 #c == column
n = 1 #n == number
a = 2 #a == checking what iteration
y = ["count1","count2","count3","count4","count5"]
for count in y:
if a%2 == 0:
print ("inside if, label values", r, c)
Label(edit_recipe_window, text="Ingredient " + str(n)).grid(row=r, column=c)
c += 1
print("inside if, entry values",r,c)
entry_box= Entry(edit_recipe_window)
entry_box.grid(row=r, column=c)
entry_box.insert(0, count)
c = 0
a += 1
else:
print ("inside else, label values", r, c)
Label(edit_recipe_window, text="Quantity and Unit " + str(n)).grid(row=r, column=c)
c += 1
print ("inside else, entry values", r, c)
quantity_box = Entry(edit_recipe_window)
quantity_box.grid(row=r, column=c)
quantity_box.insert(0, count)
c = 0
r += 1
a += 1
n += 1
which will output this for 5-valued y
inside if, label values 1 0
inside if, entry values 1 1
inside else, label values 1 0
inside else, entry values 1 1
inside if, label values 2 0
inside if, entry values 2 1
inside else, label values 2 0
inside else, entry values 2 1
inside if, label values 3 0
inside if, entry values 3 1
As you can see, first it puts Label
and Entry
in if
, then they got overwritten by Label
and Entry
in else
.
You might want to use r += 1
at the end of your if
to get rid of overwriting your widgets.
Upvotes: 2