猿问

使用itemcget在tkinter中获取单个列表框项目属性?

我编写了以下代码来绑定事件并对单个列表框项目执行操作。


import tkinter as tk


root = tk.Tk()

custom_list = tk.Listbox(root)

custom_list.grid(row=0, column=0, sticky="news")


def onselect_listitem(event):

    w = event.widget

    index = int(w.curselection()[0])

    value = w.get(index)

    print(index, value, " color : ",custom_list.itemcget(index,'background'))

    custom_list.itemconfig(index, fg='gray', selectforeground="gray")


custom_list.bind('<Double-Button-1>', onselect_listitem)


for k in range(20):

    custom_list.insert(k, " --------- " + str(k))


root.mainloop()

在itemconfig正常工作的同时,我无法使用itemcget获取背景属性。其他一切都在工作。有人可以告诉我有什么问题吗?我正在尝试通过列表框中项目的索引获取当前项目的背景色。与custom_list.itemcget的部分不打印任何内容。


人到中年有点甜
浏览 585回答 1
1回答

临摹微笑

.itemcget(index, option)检索列表框中特定行的选项值之一。有关选项值,请参见itemconfig下文。如果尚未为给定行设置给定选项,则返回值将为空字符串。因此,由于您尚未设置该background选项,因此itemcget将返回一个空字符串。您可以通过将打印更改为来查看此工作custom_list.itemcget(index,'fg')。第一次双击时会收到一个空字符串,因为您尚未设置它,而第二次则显示gray。
随时随地看视频慕课网APP

相关分类

Python
我要回答