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

标签 python tkinter colors listbox

我编写了以下代码来绑定(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/

相关文章:

python - 清除 Tkinter TEXT 小部件使用的 RAM

html - 如何让一个overlay div完全覆盖下面的div?

ios - 在 objective-c 中更改导航状态栏文本颜色时出错

python - 如何在顶级窗口python上创建垂直和水平滚动条

Python:引用 Pmw RadioSelect 中的单个标签

c# - 将旧的 VB6 QBColor 函数翻译成 C#

python - 将 Flask SQLAlchemy 模型与常规 SQLAlchemy 结合使用

Python Curses - 模块 'curses' 没有属性 'LINES'

python - 葡萄牙语编码 ã、ê、ç、á

python - python 3.4中strptime的类型错误