在我的代码早期,我的函数成功地将列表框元素的颜色更改为灰色,具体取决于用户是否选择。它变为灰色,因此用户无法重新选择同一项目,因此我正在尝试创建一个 get 在列表框中指定索引值的bg颜色的函数。
。bground = ListboxName[index]['bg']
if bground == 'gray':
print('bg is gray')
else:
print('bg is NOT gray')
我无法工作的代码行是:bground = ListboxName[index]['bg']
有任何想法吗?请注意,我不想使用课...
我也尝试过bground = ListboxName[index, 'bg']
和bground = ListboxName(index)['bg']
。
如果要获得单个项目的选项,请使用itemcget
。假设您的小部件被命名为ListBoxName
,并且您已经正确计算了该项目的索引,则看起来像这样:
bground = ListBoxName.itemcget(index, "background")
这是一个完整的示例,当您单击项目时将显示颜色:
import tkinter as tk
import random
def handle_click(self):
curselection = listbox.curselection()
index = curselection[0]
color = listbox.itemcget(index, "background")
label.configure(text="color: {}".format(color))
root = tk.Tk()
label = tk.Label(root, anchor="w")
listbox = tk.Listbox(root)
label.pack(side="top", fill="x")
listbox.pack(fill="both", expand=True)
listbox.bind("<<ListboxSelect>>", handle_click)
for item in range(20):
color = random.choice(("red", "orange", "green", "blue", "white"))
listbox.insert("end", item)
listbox.itemconfigure("end", background=color)
root.mainloop()