1

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
RenaudC5
  • 3,553
  • 1
  • 11
  • 29
  • 1
    **1.** `listbox.pack()` has nothing to do with insert data to the `listbox`. move it to `__init__`. **2.** You'r using `OOP` notation, therefore you have to use `self.listbox`. **3.** You don't need `lambda`, change to `command=self.addValues`. **4.** Using `time.sleep(...` will block the `tkinter.mainloop()`, don't use it. – stovfl Dec 15 '19 at 12:58
  • See answer to question [Tkinter — executing functions over time](https://stackoverflow.com/questions/9342757/tkinter-executing-functions-over-time). – martineau Dec 15 '19 at 13:09

1 Answers1

1

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()

martineau
  • 119,623
  • 25
  • 170
  • 301