【问题标题】:How to configure ttk.Treeview item color in Python 3.7.3?如何在 Python 3.7.3 中配置 ttk.Treeview 项目颜色?
【发布时间】:2019-10-30 21:39:03
【问题描述】:

我想自定义 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(字体为黑色)中完全不适用。我已经在 32 位和 64 位的 Windows 7 和 10 中对此进行了测试。

我怎样才能让它在较新的版本中工作?

【问题讨论】:

  • 我在 python 3.7 中得到红色的 Foo 和蓝色的 Bar
  • 我已经在 32 位和 64 位的 Windows 10 上全新安装 Python 3.7.3 进行了测试。在这两种情况下,字体都保持黑色。

标签: python tkinter python-3.7 ttk


【解决方案1】:

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

enter image description here

【讨论】:

  • 在您发布的图片中,“Bar”的字体颜色应为蓝色,“Foo”应为红色,但它们是黑白(默认颜色)。
【解决方案2】:

也许我来晚了,但是……

您肯定会面临一个已知的错误,该错误会影响发布 tk v8.6.9 的 Windows Python 版本。

要解决此问题,请在您的代码之上添加此代码(在实例化 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'))

【讨论】:

    猜你喜欢
    • 2021-10-12
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 2018-07-13
    • 2012-02-08
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多