0

So I have a listbox Tkinter object in python that allows me to select multiple items and it prints out the index of what items where selected. I want to use that index to match elsewhere in my script to say something like, if item 0,2,4 were selected then run this set of code or show other attributes of the table for 0,2,4 and exclude items 1 and 3.

Here is my script:

Title = ["ABC","DEF","GHI","JKL","MNO"]

def select_title():
    print(title_list.curselection())
    root.destroy()

root = Tk()
title_list = Listbox(root, width = 100, selectmode = MULTIPLE)
i = 0
while i < len(Title):
    title_list.insert(END, Title[i])
    i += 1
title_list.pack()

my_button = Button(root, text="Select", command=select_title)
my_button.pack()

root.mainloop()

When I run it, I get this: enter image description here

If I select "ABC", "GHI" & "MNO" (indexed of 0,2,4) and press the select button I get this output printed out:

(0, 2, 4)

I want to use these for a list = [0, 2, 4] that I can index elsewhere and that is what I am having trouble figuring out. I tried putting a return function in there but that doesn't seem to work when working with this format of Tkinter objects. I would really appreciate any insight that anyone could provide. Thanks!

Update: If I adjust the code to this, see below, I still can't use the list outside the def:

Title = ["ABC","DEF","GHI","JKL","MNO"]

def select_title():
    print(title_list.curselection())
    sel = title_list.curselection()
    lst = [_ for _ in sel]
    print(lst)
    root.destroy()

root = Tk()
title_list = Listbox(root, width = 100, selectmode = MULTIPLE)
i = 0
while i < len(Title):
    title_list.insert(END, Title[i])
    i += 1
title_list.pack()

my_button = Button(root, text="Select", command=select_title)
my_button.pack()

root.mainloop()

Output:

(0, 2, 4)
[0, 2, 4]

Trying outside the def:

lst

Output:

enter image description here

Andrew Hicks
  • 572
  • 1
  • 6
  • 19

1 Answers1

0

Thank you Cool Cloud for your insight. It was crucial to get this to work.

Below is the script that worked:

Title = ["ABC","DEF","GHI","JKL","MNO"]

def select_title():
    sel = title_list.curselection()
    global lst
    lst = [_ for _ in sel]
    root.destroy()

root = Tk()
title_list = Listbox(root, width = 100, selectmode = MULTIPLE)
i = 0
while i < len(Title):
    title_list.insert(END, Title[i])
    i += 1
title_list.pack()

my_button = Button(root, text="Select", command=select_title)
my_button.pack()

root.mainloop()

lst
Andrew Hicks
  • 572
  • 1
  • 6
  • 19