简体   繁体   English

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

[英]How to configure ttk.Treeview item color in Python 3.7.3?

I want to customize the style of the sigle items in a ttk.Treeview .我想自定义ttk.Treeview Example code:示例代码:

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()

This is working perfectly in Python 3.6.8 (font is red/blue), but not at all in Python 3.7.3 (font is black).这在 Python 3.6.8(字体为红色/蓝色)中完美运行,但在 Python 3.7.3(字体为黑色)中完全无效。 I have tested this in Windows 7 and 10, both in 32 and 64 bit.我已经在 32 位和 64 位的 Windows 7 和 10 中对此进行了测试。

How can I get this working in the newer version?我怎样才能在较新的版本中使用它?

Maybe I'm a bit late here but...也许我在这里有点晚了但是......

You're surely facing a known bug affecting Windows Python builds shipping tk v8.6.9.您肯定会遇到影响 Windows Python 构建发布 tk v8.6.9 的已知错误。

To solve, add this code on top of yours (before instantiating the Treeview):要解决此问题,请将此代码添加到您的代码之上(在实例化 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'))

It's working properly no issue we run it on python 3.7x.它工作正常,我们在 python 3.7x 上运行它没有问题。 Here we attached the screenshot.这里我们附上了截图。

enter image description here在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM