Modify Listbox entries via listvariable in Tkinter

Viewed 6331

I read in a tutorial that I can separate the data from the tkinter.Listbox into my own list. I did this in the example here. But how can I manipulate the order of the Listbox-entries based on my own variablelist?

#!/usr/bin/env python3

from tkinter import *

root = Tk()
mylist = ['one', 'two', 'three']
var = StringVar(value=mylist)
box = Listbox(master=root, listvariable=var)
box.pack(fill=BOTH, expand=True)

# this need to affect the list
mylist.append('four')
mylist.remove('two')
mylist.insert(3, mylist.pop(1))

root.mainloop()

The Listbox (in the GUI) here is not affected.

As I understand there is a way that Listbox refresh absolut automaticly its content when I modify the data-list. So I don't have to touch Listbox. I only need to touch the data in the list().

Is there a way?

1 Answers

Listbox has get(), delete() and insert().
You can get value from box, remove it and put it in new place.

Or you can remove all items from box and add new items from mylist.
I think this method is more universal.

box.delete(0, 'end')
for item in mylist:
    box.insert('end', item)

Because you use listvariable so you can replace list directly in var

var.set(mylist)

Full code

from tkinter import *

root = Tk()

mylist = ['one', 'two', 'three']

var = StringVar(value=mylist)
box = Listbox(master=root, listvariable=var)
box.pack(fill=BOTH, expand=True)

mylist.append('four')
mylist.remove('two')
mylist.insert(3, mylist.pop(1))

var.set(mylist)

root.mainloop()
Related