例如,我有一個Listbox包含動態 int 值的 tkinter [1,2,3,4,5]。我已經修改了我的代碼以使其更簡單。
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)
我在每個專案的背景上做了一些條件格式。例如,所有偶數值都是紅色,所有奇數值都是綠色。串列框顏色為[red,green, red, green, red]. 效果很好。
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)
但我也在選擇專案。當我通過將前景設定為紫色來選擇專案時,我想注意。還好。但這也會將背景更改為藍色,因此它會覆寫我不想要的條件格式的背景。
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)
uj5u.com熱心網友回復:
在 for 回圈中selectbackground設定時也只需設定:bg
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/435646.html
