RenaudC5
RenaudC5

Reputation: 3829

Tkinter - update ListBox in a loop

I am new to Tkinter and I have this problem:

I want to update my ListBox with new values in a loop so the values are added to it during the loop and not only at the end.

Here is an example code of my problem:

import time
import tkinter as tk

class mainApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        listbox = tk.Listbox(self)
        button3 = tk.Button(self, text="addValues",
                            command=lambda : self.addValues(listbox))
        button3.pack()

    def addValues(self,listbox):
        for i in range(10):
            time.sleep(1)
            listbox.insert(tk.END, str(i))
            listbox.pack()


app = mainApp("test")
app.mainloop()

Here I want the Frame to update each time a value is added to the ListBox.

Upvotes: 1

Views: 672

Answers (1)

martineau
martineau

Reputation: 123423

You can't program a tkinter application the same procedural way you're used to because everything in it must occur while its mainloop() is running. Tkinter is an event-driven framework for writing GUIs.

Here's how to do what you want using the universal widget method after() it has to schedule a callback to a method that does the insertion after a short delay (and then sets up another call to itself if the LIMIT hasn't been reached).

import time
import tkinter as tk

LIMIT = 10
DELAY = 1000  # Millisecs


class mainApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        listbox = tk.Listbox(self)
        listbox.pack()
        button3 = tk.Button(self, text="addValues",
                            command=lambda : self.addValues(listbox))
        button3.pack()

    def addValues(self, listbox):
         self.after(DELAY, self.insertValue, listbox, 0, LIMIT)

    # ADDED
    def insertValue(self, listbox, value, limit):
        if value < limit:
            listbox.insert(tk.END, str(value))
            self.after(DELAY, self.insertValue, listbox, value+1, limit)


app = mainApp("test")
app.mainloop()

Upvotes: 1

Related Questions