我有一个显示一些对象的列表框:
# extra is some array of 'extra' objects I get from a database
self.extrasList = Listbox(self, selectmode='multiple')
self.extrasList.pack(fill=X, expand=True)
for extra in extras:
self.extrasList.insert(END, extra)
extra
个对象的__str__
被覆盖,所以它们显示得很好。
然而,当我稍后再做:
selection = self.extrasList.curselection()
extra = self.extrasList.get(selection[0]) #this is now a string rather than the proper 'extra' object
有没有办法让对象退出列表框? 而不是字符串?
我唯一能找到的就是手动保持列表框和其他列表同步。但这可能是错误的。
答案 0 :(得分:1)
不,没有办法将列表框中的数据作为字符串以外的任何内容。
答案 1 :(得分:0)
您可以尝试这样的事情:将对象放入字典(字符串作为键,对象作为值)并将键插入列表框,然后使用listbox.selection_get().split()
检索选定的键并使用它们从字典中获取所需的对象。
import tkinter as tk
root = tk.Tk()
def print_selection(event):
for key in listbox.selection_get().split():
print(extras[key])
extras = {
'object1': 1,
'object2': 2,
}
listbox = tk.Listbox(root, selectmode='multiple')
for key in extras:
listbox.insert('end', key)
listbox.grid(row=0, column=0)
listbox.bind('<Key-Return>', print_selection)
tk.mainloop()
答案 2 :(得分:0)
class Test:
def __init__(self,name):
self.name=name
def __str__(self):
return self.name
test=Test('MY OBJECT')
假设您已插入列表框测试对象,它将在字符串框中显示为字符串listbox = ['MY_OBJECT']名称。
您可以像在列表框中那样轻松获得对象-> 首先,将测试对象保存在一个空列表中:
my_list=[test]
之后,您可以使用for循环轻松地了解哪个对象已选中或未选中:
for get_string in listbox:
for obj in my_list:
if get_string == obj.__str__():
print(f' You Selected {obj}')