M4X
M4X

Reputation: 3

Why does python only shows the first half of the list in tkinter?

I tried to write a program, which shows a list of integers in a table in a new tkinter window by pressing a button. Than I run it, only the first half of the list was showed, but no errors was indicated. I tried to double the body of the for-loop, but one at uneven number of integers of the list and two at a even were missing. Here is the isolated problem:

from tkinter import * 

def table():
   filewin = Toplevel(root)
   x = 1
   numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

   for i in numbers:
       Label(filewin, text = ("Value", x, ":")).grid(column = 0, row = i)
       Label(filewin, text = (liste.pop(0),"cm")).grid(column = 1, row = i)
       x += 1


root = Tk()

Button(root, text = 'show list', command = table).pack()

root.mainloop()

Upvotes: 0

Views: 35

Answers (3)

KJTHoward
KJTHoward

Reputation: 876

Because when you pop off one of the numbers the list that i is iterating through gets shorter, that's why it terminates early. Also instead of using x as a separate variable to keep track of the iterations, you can use enumerate. Doing this, and not popping off the number, just displaying it, fixes your issue:

from tkinter import * 

def table():
   filewin = Toplevel(root)

   numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

   for i,number in enumerate(numbers):
       Label(filewin, text = ("Value", i+1, ":")).grid(column = 0, row = i)
       Label(filewin, text = (number,"cm")).grid(column = 1, row = i)



root = Tk()

Button(root, text = 'show list', command = table).pack()

root.mainloop()

Upvotes: 1

Maximouse
Maximouse

Reputation: 4383

liste.pop(0) removes the first value of the list. You probably don't want to do that. I think that you should use enumerate():

def table():
   filewin = Toplevel(root)
   numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

   for i, n in enumerate(numbers):
       Label(filewin, text = ("Value", i + 1, ":")).grid(column = 0, row = i)
       Label(filewin, text = (n, "cm")).grid(column = 1, row = i)

Upvotes: 0

Phoenixo
Phoenixo

Reputation: 2113

Here I created liste as an independant copy of numbers. If you used the same list, you would have only half the list printed since you pop one element out of the list at each iteration.

from tkinter import * 

def table():
    filewin = Toplevel(root)
    x = 1
    numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    liste = numbers.copy()
    for i in numbers:
        Label(filewin, text = ("Value", x, ":")).grid(column = 0, row = i)
        Label(filewin, text = (liste.pop(0),"cm")).grid(column = 1, row = i)
        x += 1

root = Tk()

Button(root, text = 'show list', command = table).pack()

root.mainloop()

Upvotes: 0

Related Questions