如何在Python 3.7.3中配置ttk.Treeview项目颜色?

时间:2019-06-17 09:52:23

标签: python tkinter python-3.7 ttk

我想自定义ttk.Treeview中单项的样式。示例代码:

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
tree = ttk.Treeview(root)

# Inserted at the root, program chooses id:
tree.insert('', 'end', 'foo', text='Foo', tags=['red_fg'])

# Inserted underneath an existing node:
tree.insert('foo', 'end', text='Bar', tags=['blue_fg'])

# tag's order can be important
tree.tag_configure("red_fg", foreground="red")
tree.tag_configure("blue_fg", foreground="blue")

tree.pack()
root.mainloop()

这在Python 3.6.8(字体为红色/蓝色)中完美地工作,但在Python 3.7.3(字体为黑色)中则完全没有。我已经在Windows 7和10(32位和64位)中对此进行了测试。

如何在更新的版本中使用它?

2 个答案:

答案 0 :(得分:0)

也许我来的有点晚了但是...

您肯定会遇到影响 Windows Python 构建并发布 tk v8.6.9 的已知错误。

要解决此问题,请将此代码添加到您的代码之上(在实例化 Treeview 之前):

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
s = ttk.Style()

#from os import name as OS_Name
if root.getvar('tk_patchLevel')=='8.6.9': #and OS_Name=='nt':
    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 s.map('Treeview', query_opt=option) if elm[:2] != ('!disabled', '!selected')]
    s.map('Treeview', foreground=fixed_map('foreground'), background=fixed_map('background'))

答案 1 :(得分:-1)

它工作正常,没问题,我们在python 3.7x上运行它。在这里,我们附上了屏幕截图。

enter image description here