【发布时间】:2022-10-21 04:13:09
【问题描述】:
我有一个包含动态 int 值的 tkinter Listbox,例如 [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))
# conditional 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)
【问题讨论】: