I have a tkinter Listbox
containing dynamic int valuesfor example [1,2,3,4,5]
. I have adapted my code to make it simpler.
self.edt_shots = ttk.Listbox(
self,
height=7,
exportselection=False,
selectforeground="purple",
activestyle=UNDERLINE,
#selectbackground="white", # TRANSPARENT needed here?
)
self.edt_shots.grid(row=3, column=3, rowspan=5)
I do some conditonnal formatting on the background of each item.
So for example all even values would be red and all odd values would be green.
The listbox colors would be [red,green, red, green, red]
.
That works well.
lst=[1,2,3,4,5]
for i, name in enumerate(lst):
self.edt_shots.insert(i, str(name))
# conditionnal formatting
self.edt_shots.itemconfig(
i,
bg="green"
if i%2 == 1
else "red"
)
self.edt_shots.bind("<<ListboxSelect>>", self.on_edt_shots_change)
But I am also selecting items. I want to notice when I select items by setting the foreground to purple. Still good. But that also changes the background to Blue so it overwrites the background from my conditonal formatting which I don't want.
def on_edt_shots_change(self, event):
"""handle item selected event"""
if len(self.edt_shots.curselection()) <= 0:
return
index = self.edt_shots.curselection()[0] 1
self.edt_shots.select_clear(0, "end")
self.edt_shots.selection_set(index)
self.edt_shots.see(index)
self.edt_shots.activate(index)
self.edt_shots.selection_anchor(index)
CodePudding user response:
Just set the selectbackground
as well when setting the bg
in the for loop:
lst = [1, 2, 3, 4, 5]
for i, name in enumerate(lst):
self.edt_shots.insert(i, str(name))
# conditionnal formatting
bg = "green" if i%2 == 1 else "red"
self.edt_shots.itemconfig(i, bg=bg, selectbackground=bg)