我试图使用for循环创建一个用于制作标签和条目的for循环。这是代码:
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
这会产生数量+单位2的标签,这不是期望的结果。
答案 0 :(得分:2)
如果您使用print
进行调试,则会看到您将每个if-else
对上的小部件放在彼此的顶部。
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
将为5值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
正如您所看到的,首先它将Label
和Entry
放入if
,然后Label
和Entry
覆盖了else
}。
您可能希望在r += 1
的末尾使用if
来摆脱覆盖您的小部件。