获取listbox元素的bg颜色?

问题描述 投票:0回答:1

在我的代码中,我有一个函数可以成功地将列表框元素的颜色更改为灰色,具体取决于用户是否选择了该颜色。它变为灰色,因此用户无法重新选择相同的项目,因此我尝试创建一个函数,在列表框中获取指定索引值的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']

python tkinter background listbox
1个回答
0
投票

如果您想获得单个项目的选项,请使用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()
© www.soinside.com 2019 - 2024. All rights reserved.