おそらくこれらの記事が該当するでしょう。
Python 3.7.3 以後の tkinter に入ったバグのようです。
python : tkinter treeview colors are not updating
Tkinter Treeview issue when inserting rows with tags
Looks like the issue was caused by a newer version of tkinter, not a newer version of Python. This was reported in https://bugs.python.org/issue36468 and https://core.tcl-lang.org/tk/info/509cafafae
Here is a proposed solution. It should be both backward and forward compatible:
この問題は、Python の新しいバージョンではなく、tkinter の新しいバージョンが原因のようです。これは https://bugs.python.org/issue36468 と https://core.tcl-lang.org/tk/info/509cafafae で報告されています。
ここに提案された解決策があります。それは、後方互換性と前方互換性の両方を持っている必要があります。
def fixed_map(option):
# Fix for setting text colour for Tkinter 8.6.9
# From: https://core.tcl.tk/tk/info/509cafafae
#
# 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')]
style = ttk.Style()
style.map('Treeview', foreground=fixed_map('foreground'), background=fixed_map('background'))
上記を質問記事のソースに適用したら、それらしい動作になるようです。
項目数は増やしてみました。
import tkinter as tk
from tkinter import ttk
def fixed_map(option):
# Fix for setting text colour for Tkinter 8.6.9
# From: https://core.tcl.tk/tk/info/509cafafae
#
# 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')]
if __name__ == '__main__':
obj = ttk.tkinter.Tk()
style = ttk.Style()
style.map('Treeview', foreground=fixed_map('foreground'), background=fixed_map('background'))
tree = ttk.Treeview(
obj,
show = "headings",
)
tree_item = {
"No.":40,
"Name":80,
}
tree["columns"]=tuple(range(1,len(tree_item)+1))
for i, item in enumerate(tree_item.items()):
name, width = item
tree.heading(i+1,text=name)
tree.column(i+1,minwidth = width, width = width, stretch = False, anchor = tk.CENTER)
value_list = [
'aaa','bbb','ccc','ddd','eee','fff',
]
for i,v in enumerate(value_list):
tree.insert("",index = "end",tags = i,value=[i+1,v])
if i%2 == 0:
tree.tag_configure(i,background = 'yellow')
tree.pack()
obj.mainloop()
Python 3.8.2 で以下のようになりました。
