tkinter 列表框选定样式为透明
我有一个包含动态 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)
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 conditional 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))
# 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)
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 conditional 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需在 for 循环中设置
bg
时也设置selectbackground
即可:Just set the
selectbackground
as well when setting thebg
in the for loop: