Alex Weinstein
Alex Weinstein

Reputation: 79

Python and Listbox (GUI)

I have constructed a listbox using tkinter Now I want the user to click on an item in the listbox that creates a variable with the selection.

listbox.bind('<ButtonRelease-1>', get_list)

def get_list(event):
    index = listbox.curselection()[0]
    seltext = listbox.get(index)
    print(seltext)

This properly prints out the selection. However, I am unable to get the "seltext" out of the function and able to use it later in the code. Someone recommended the get_list(event) however I don't know where event came from. Appreciate the help

EDIT:

   for f in filename:
                with open(f) as file_selection:
                    for line in file_selection:
                        Man_list = (line.split(',')[1])

                        listbox.insert(END, Man_list)

                file_selection.close()



        def get_list(event):
            global seltext
            # get selected line index
            index = listbox.curselection()[0]
            # get th e line's text
            global seltext
            seltext = listbox.get(index)



        # left mouse click on a list item to display selection
        listbox.bind('<ButtonRelease-1>', get_list)

Upvotes: 1

Views: 1244

Answers (1)

Hobbes
Hobbes

Reputation: 404

This is an issue with how you are structuring your code more than anything. Event handlers are not built to return values. Use a global variable or class property to retrieve and store the value. A global variable can be set like so:

from Tkinter import *

def get_list(event):
    global seltext
    index = listbox.curselection()[0]
    seltext = listbox.get(index)

root = Tk()
listbox = Listbox(root)
listbox.pack()
listbox.bind('<ButtonRelease-1>', get_list)

for item in ["one", "two", "three", "four"]:
    listbox.insert(END, item)

seltext = None

root.mainloop()

But a class property is the better option. Your Tkinter application should be modular to ensure everything is easily accessible and prevent problems like this. You can set variables to self and access them later that way.

from Tkinter import *

class Application(Tk):
    def __init__(self):
        Tk.__init__(self)
        listbox = Listbox(self)
        listbox.pack()
        listbox.bind('<ButtonRelease-1>', self.get_list)

        for item in ["one", "two", "three", "four"]:
            listbox.insert(END, item)

        self.listbox = listbox # make listbox a class property so it
                               # can be accessed anywhere within the class

    def get_list(self, event):
        index = self.listbox.curselection()[0]
        self.seltext = self.listbox.get(index) 

if __name__ == '__main__':
    app = Application()
    app.mainloop()

Upvotes: 1

Related Questions