6

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
  • you can remove all items from box and add new items from mylist. Listbox on effbot.org Commented Nov 19, 2017 at 23:37

1 Answer 1

6

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

import tkinter as tk  # PEP8: `import *` is not preferred

root = tk.Tk()

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

var = tk.StringVar(value=mylist)
box = tk.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()
Sign up to request clarification or add additional context in comments.

1 Comment

Ah I see. The mechanism is not 100% automatic. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.