user3840530
user3840530

Reputation: 294

Get individual listbox item properties in tkinter using itemcget?

I wrote the below code to bind event and do operations on individual listbox items.

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()

I am having trouble using itemcget to get the background properties while itemconfig works properly. Everything else is working. Can someone tell me if there is something wrong? I am trying to obtain the current item background color via index of the item in the listbox. The part with custom_list.itemcget doesn't print anything.

Thanks

Upvotes: 1

Views: 1716

Answers (1)

fhdrsdg
fhdrsdg

Reputation: 10552

From the 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.

So since you haven't set the background option, itemcget returns an empty string. You can see this working by changing the print to custom_list.itemcget(index,'fg'). The first time you doubleclick you get an empty sting because you haven't set it, the second time it prints gray.

Upvotes: 2

Related Questions