João Sousa
João Sousa

Reputation: 41

get Object from a tkinter listbox

I've created a class called "client" with a def __ str__ so I can add a list of clients on a listbox and display the client's name instead of the <object at 0x etc> memory name.

The problem is when I add the client to a listbox, I want to get the selection from the list with an event function, what comes from the listbox isn't the object itself, but the string from __ str__. How can I change my code to get the object instance instead of the string name?

class PageOne(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        label = Label(self, text="Clientes", font=LARGE_FONT)
        label.pack(pady=10, padx=10)
        button = Button(self, text="Voltar", 
                        command=lambda:controller.show_frame(StartPage))
        button.place(x=330, y=50)

        self.listbox = Listbox(self, height=17, width=25)
        self.listbox.place(x=25, y=110)

        scrollbar = Scrollbar(self.listbox, orient="vertical")
        scrollbar.config(command=self.listbox.yview)
        scrollbar.place(height=273, x=134)

        self.listbox.config(yscrollcommand=scrollbar.set)
        self.listbox.bind('<<ListboxSelect>>', self.onselect)

        for client in clients:
            self.listbox.insert(END, client)

        # creating the gui
        label = Label(self, text="Nome:", font=MEDIUM_FONT)
        label.place(x=250, y=120)
        self.name_var = StringVar()
        self.name_var.set(clients[0].name)
        name_label = Label(self, textvariable=self.name_var, font=MEDIUM_FONT)
        name_label.place(x=330, y=120)

    def onselect(self, evt):
        w = self.listbox.get(self.listbox.curselection())
        self.name_var.set(w)
        print(w)

I want to create a GUI so I could alter the name/age/country from the client every time I press on the listbox, like an information GUI about the selected client. That's why I need the object so I can edit the StringVars I created.

The "w" variable is just the string to the name of my client, instead of the client itself, that's what I want to change and don't know how.

class Client:
    def __init__(self, name, gsm, local, tp, email=None, served=False):
        self.name = name
        self.gsm = gsm
        self.email = email
        self.local = local
        self.tp = tp
        self.served = served

    def __str__(self):
        return self.name

Upvotes: 0

Views: 402

Answers (1)

Jo&#227;o Sousa
Jo&#227;o Sousa

Reputation: 41

ANSWER BY @stovfl:

get the object instance instead of the string name? Do client_object = clients[self.listbox.curselection()[0]]

Upvotes: 1

Related Questions