1

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It works now! Just wondering if there is no default value that should be returned. Anyway, got it. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.