我编写了以下代码来绑定(bind)事件并对各个列表框项执行操作。
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 的部分不会打印任何内容。
谢谢
最佳答案
来自 New Mexico tech Tkinter reference :
.itemcget(index, option)
- Retrieves one of the option values for a specific line in the listbox. For option values, see
itemconfig
below. If the given option has not been set for the given line, the returned value will be an empty string.
因此,由于您尚未设置 background
选项,itemcget
返回一个空字符串。您可以通过将打印更改为 custom_list.itemcget(index,'fg')
来查看此操作的工作情况。第一次双击时,您会得到一个空字符串,因为您尚未设置它,第二次它会打印灰色
。
关于python - 使用 itemcget 在 tkinter 中获取单个列表框项目属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51243498/