0

I'm trying to write a program that returns the index of a selected Listbox item to the function where the bind function was called.

The below program simply prints the index of the selected item inside the get_index function once the item is clicked; however, I want the index to be returned to the main function rather than being contained in the get_index function. Is what I'm trying to accomplish even possible?

import tkinter as tk

def get_index(event):
    selection = event.widget.curselection()
    if selection:
        index = selection[0]
        print(index)    # Want to return here instead of print
    else:
        pass

def main():
    root = tk.Tk()
    root.geometry("300x150")

    my_list = tk.Listbox(root)
    my_list.pack(pady=15)

    options = [
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
    ]

    for option in options:
        my_list.insert("end", option)

    my_list.bind("<<ListboxSelect>>", get_index)

    root.mainloop()

if __name__ == "__main__":
    main()
gskn13
  • 49
  • 2
  • 10
  • 1
    I don't think you should use return here, you should declare a global variable and assign the index number to it –  Jul 22 '21 at 16:46
  • @Sunjay I had considered using a global variable if I wasn't able to return. Thanks for the suggestion! – gskn13 Jul 22 '21 at 16:51

1 Answers1

1

How can I return the index of a tkinter Listbox selection back to the function where the bind was called?

The short answer is: you can't.

Bound functions are not called in the context of the function where the binding was made. Anything a bound function returns will be ignored by tkinter.

Since you are not using classes, your only option is to use a global variable.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • So if I was using classes, I would be able to accomplish, at least in some capacity, what I'm wanting to do? Why would that be (if not too complicated of an explanation)? – gskn13 Jul 22 '21 at 16:56
  • 2
    @gskn13 I think what Bryan meant was, if you were using classes, you would store the data as a class attribute, rather than `global` variable. Using classes, does not let you achieve what you want, these callback function returns are ignored, like said. – Delrius Euphoria Jul 22 '21 at 17:14
  • @CoolCloud Oh okay, that would make sense. Would there be any advantages to using classes and attributes compared to functions and global variables? – gskn13 Jul 22 '21 at 17:18
  • 2
    @gskn13 Generally, [global variables are _evil_](https://stackoverflow.com/q/19158339/13382000), but for small projects it is fine(neglibible). If you know classes, it is better to use OOP. – Delrius Euphoria Jul 22 '21 at 17:19
  • 1
    @gskn13: if you were using classes, you could use an instance attribute to store the data. – Bryan Oakley Jul 22 '21 at 17:22