我试图使用标记和tag_configure将颜色设置为treeview对象中的行。
先前曾讨论过行的着色问题,这是一个相当古老的问题,似乎不再适用于Python3:
ttk treeview: alternate row colors
我补充了一个简短的例子。对于我来说,所有行都是白色的,这与我是在insert命令之前还是之后执行tag_configure无关。
import tkinter as tk
import tkinter.ttk as ttk
root = tk.Tk()
w = tk.Label(root, text="Hello, world!")
w.pack()
lb= ttk.Treeview(root, columns=['number', 'text'], show="headings", height =20)
lb.tag_configure('gr', background='green')
lb.column("number", anchor="center", width=10)
lb.insert('',tk.END, values = ["1","testtext1"], tags=('gr',))
lb.insert('',tk.END, values = ["2","testtext2"])
lb.pack()
root.mainloop()
是什么改变了还是我错过了什么?
编辑:似乎是一个新的已知bug,有了解决办法,但我无法理解这个问题:https://core.tcl-lang.org/tk/tktview?name=509cafafae
EDIT2:,我现在使用的是tkVersion8.6.10 (Build hfa6e2cd_0,Channel conda-forge)和python3.7.3。有人能用这个版本的python和tk复制这个错误吗?
发布于 2020-04-26 17:02:03
您不再需要使用fixed_map,bug是在tkinter8.6版本中修复的。下面的代码对于我使用tkinter 8.6和python 3.8.2在Linux中运行很好。
import tkinter as tk
import tkinter.ttk as ttk
def fixed_map(option):
return [elm for elm in style.map("Treeview", query_opt=option) if elm[:2] != ("!disabled", "!selected")]
root = tk.Tk()
style = ttk.Style()
style.map("Treeview", foreground=fixed_map("foreground"), background=fixed_map("background"))
w = tk.Label(root, text="Hello, world!")
w.pack()
lb= ttk.Treeview(root, columns=['number', 'text'], show="headings", height =20)
lb.tag_configure('odd', background='green')
lb.tag_configure('even', background='lightgreen')
lb.column("number", anchor="center", width=10)
lb.insert('', tk.END, values = ["1","testtext1"], tags=('odd',))
lb.insert('', tk.END, values = ["2","testtext2"], tags=('even',))
lb.insert('', tk.END, values = ["3","testtext3"], tags=('odd',))
lb.insert('', tk.END, values = ["4","testtext4"], tags=('even',))
lb.pack()
root.mainloop()
发布于 2020-04-25 08:03:04
Chuck666的这个答案起了作用:https://stackoverflow.com/a/60949800/4352930
这段代码起作用
import tkinter as tk
import tkinter.ttk as ttk
def fixed_map(option):
# Returns the style map for 'option' with any styles starting with
# ("!disabled", "!selected", ...) filtered out
# style.map() returns an empty list for missing options, so this should
# be future-safe
return [elm for elm in style.map("Treeview", query_opt=option)
if elm[:2] != ("!disabled", "!selected")]
root = tk.Tk()
style = ttk.Style()
style.map("Treeview",
foreground=fixed_map("foreground"),
background=fixed_map("background"))
w = tk.Label(root, text="Hello, world!")
w.pack()
lb= ttk.Treeview(root, columns=['number', 'text'], show="headings", height =20)
lb.tag_configure('gr', background='green')
lb.column("number", anchor="center", width=10)
lb.insert('',tk.END, values = ["1","testtext1"], tags=('gr',))
lb.insert('',tk.END, values = ["2","testtext2"])
lb.pack()
root.mainloop()
我希望Chuck666在这里复制他的答案,因为我认为如果他出现的话,他已经赚到了奖金。
https://stackoverflow.com/questions/61373260
复制相似问题