1

I am a new python user. I'm used to programing on matlab. I've trying to make a simple GUI with Tkinter pack, but I'm having some problems with that. I had already read and searched what i want but I couldn't develop it.

What I'm trying to do is to make a listbox and when I choose one (or more) options the index be returned (and stored) as a variable (array or vector) that could be used to indexing another array.

The best result I got was a listbox where the index were printed, but not stored as a variable (at least it hasn't been shows in the variables list)

I'm using spyder (anaconda).

I tryied a lot of codes and I don't have this anymore.

Sorry for the dumb question. I guess I still thinking in a Matlab way to write

2 Answers 2

1

To keep this application simple, your best option is to get the listbox selection when you want to do something with it:

from tkinter import Tk, Listbox, MULTIPLE, END, Button

def doStuff():
    selected = lb.curselection()
    if selected: # only do stuff if user made a selection
        print(selected)
        for index in selected:
            print(lb.get(index)) # how you get the value of the selection from a listbox

def clear(lb):
    lb.select_clear(0, END) # unselect all

root = Tk()

lb = Listbox(root, selectmode=MULTIPLE) # create Listbox
for n in range(5): lb.insert(END, n) # put nums 0-4 in listbox
lb.pack() # put listbox on window

# notice no parentheses on the function name doStuff
doStuffBtn = Button(root, text='Do Stuff', command=doStuff)
doStuffBtn.pack()

# if you need to add parameters to a function call in the button, use lambda like this
clearBtn = Button(root, text='Clear', command=lambda: clear(lb))
clearBtn.pack()

root.mainloop()

I've also added a button to clear the listbox selection because you cannot unselect items by default.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much. your code solve my problems. Now I got how this combination of button and listbox works. I'm used to build GUI with GUIDE toolbox from Matlab where the functions of the widgets are ready to use without configuring it.
0

First, import tkinter, then, create the listbox. Then, you can use curselection to get the contents of the listbox.

import tkinter as tk
root = tk.Tk() #creates the window
myListbox = tk.Listbox(root, select=multiple) #allows you to select multiple things
contentsOfMyListbox = myListbox.curselection(myListbox) #stores selected stuff in tuple

See the documentation here.

1 Comment

curselection is a method of the Listbox class and must be called like <Listbox object>.curselection()

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.