AndreasT
AndreasT

Reputation: 9801

Python Tkinter: Update scrolled Listbox - wandering scroll position

I wanted to display a long list of string items that is regularly updated in a scrollable GUI Window. Loving the use of free included batteries I used Tkinter, and ran into a few problems:

I solved this, and will share the solution as an answer to this question. If you know a better way, please post an improved answer.

Upvotes: 1

Views: 1417

Answers (1)

AndreasT
AndreasT

Reputation: 9801

The trick is, to save the yview of the listbox, modify the content, and then move back to that position. So, here is my solution using Tkinter:

from Tkinter import * # I do not like wild imports, but everyone seems to do it

root = Tk()

scrollbar = Scrollbar(root, orient=VERTICAL) # yes, do this first...
listb = Listbox(root, yscrollcommand=scrollbar.set) # ...because you need it here
scrollbar.config(command=listb.yview)
scrollbar.pack(side=RIGHT, fill=Y)
listb.pack(fill=BOTH, expand=YES) # convince the listbox to resize

item_list = range(400)

for item in item_list:
    listb.insert(item)

exponent = 0
def update_list():
    global exponent
    vw = listb.yview() # Save the current position(percentage) of the top left corner
    for i in item_list:
        listb.delete(i)
        listb.insert(i, i * 10**exponent)
    listb.yview_moveto(vw[0]) # go back to that position
    exponent += 1
    root.after(1000, update_list)

root.after(1000, update_list)
root.mainloop()

Upvotes: 2

Related Questions