GabrielBR
GabrielBR

Reputation: 25

Tkinter Python listbox

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

Upvotes: 1

Views: 5607

Answers (2)

Nelson
Nelson

Reputation: 952

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.

Upvotes: 1

auden
auden

Reputation: 1157

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.

Upvotes: 0

Related Questions