tkinter ttk树状视图彩色行

问题描述 投票:1回答:1

我正在尝试使用标签和tag_configure为tkinter树视图对象中的行设置颜色。

之前有过关于为行着色的讨论,该讨论很旧,似乎不再适用于Python3:

ttk treeview: alternate row colors

我添加了一个简短的示例。对我来说,所有行都保持白色,与我在插入命令之前还是之后执行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()

发生了什么变化或我缺少什么?

编辑:似乎这是一个新的已知错误,具有解决方法,但我无法正常工作:https://core.tcl-lang.org/tk/tktview?name=509cafafae

EDIT2:我现在正在使用tk版本8.6.10(Build hfa6e2cd_0,Channel conda-forge)和python 3.7.3。任何人都可以使用此版本的python和tk重现此错误吗?

python tkinter treeview ttk
1个回答
0
投票

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()
© www.soinside.com 2019 - 2024. All rights reserved.