Akash Nil
Akash Nil

Reputation: 703

How to update Tkinter Listbox text variable

I want to update an listbox data automatically. what's wrong with my code??

import Tkinter,time
from Tkinter import *
window=Tk()
box=Tkinter.Listbox(window,width=17,height=12,fg="black")
data=0
box.grid(row=0,column=0)
box.insert(Tkinter.END,data)
def monitor():
    global data
    print data
    while True:
        time.sleep(1)
        data=data+1
        box.update()
window.after(10,monitor)
window.mainloop()

Upvotes: 1

Views: 4483

Answers (1)

R4PH43L
R4PH43L

Reputation: 2202

First of all please be consistent with your code.

  • Use one kind of import for one library
import Tkinter as tk

Second, while True constructs are to be ommitted if possible. You used window.after in your main routine, why not do that in your monitor function as well?

def monitor():
    global data


    # do the work that needs to be done...

    # after uses ms, to calling monitor 
    # after 1000 ms is the same as calling 
    # sleep(1) in your while true construct
    window.after(1000, monitor) 

Finally, zodo is right, you need to update the listbox data by e.g. delete / insert combination.

import Tkinter as tk
window = tk.Tk()
box = tk.Listbox(window, width=17, height=12, fg="black")
data = 0
box.grid(row=0, column=0)
box.insert(tk.END, data)

def monitor():
    global data

    print data

    data = data + 1
    # Update the listbox
    # 1. clear all
    box.delete(0, tk.END)
    # 2. insert new data
    box.insert(tk.END, data)
    window.after(1000, monitor)

window.after(10, monitor)
window.mainloop()

Upvotes: 3

Related Questions