Reputation: 713
I have learned that you can put objects into a tkinter Listbox.
What I want to know is how to show them in the Listbox with a meaningful name. At the moment I have a class 'Character' and all I get in the Listbox is <Character.Character object at 0x002CF6D0>
. If I retrieve it, I get that object back out, which is what I want.
But that item in the Listbox isn't very useful to the user. Is there a way that I can give it a name of my choosing, while still being able to retrieve the object?
Upvotes: 0
Views: 1210
Reputation: 386342
You can't put objects in a listbox. The listbox knows nothing about python objects and can only display strings. If you try to insert an object into a listbox, tkinter will convert that object to a string, and then store the string (and only the string) in the listbox. You will not be able to retrieve the actual object later.
However, if you want it to automatically convert your object to a string with a name of your choosing, you can override the __str__
method of your class. That function is what tkinter uses to convert the object to a string before inserting it into a widget.
For example, here's a class definition that will return the name attribute when the object is converted to a string:
class Character():
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
Here is an example of using that class in a tkinter program.
import tkinter as tk
root = tk.Tk()
listbox = tk.Listbox(root)
listbox.pack(fill="both", expand=True, padx=2, pady=2)
c1 = Character("Inigo Montoya")
c2 = Character("Fezzik")
listbox.insert("end", c1)
listbox.insert("end", c2)
root.mainloop()
Upvotes: 1