繁体   English   中英

如何通过标签更改 Treeview 中项目的背景/前景?

[英]How to change background/foreground of item in Treeview by tag?

我想在 Treeview 中为标签应用不同的背景,但是当我将标签设置为例如“减号”并尝试将标签配置为具有黑色背景时,它仍然返回白色背景。

我尝试应用样式并将背景设置为所需的 RGB 到 Treeview,但背景保持白色。 我还尝试设置标签并将标签背景配置为所需的 RGB,但它仍然返回为白色!

    for row in rows:
        self.treeplan.insert('', 'end', text=str(cpt),
                             values=(row[1], row[2], row[3], row[4], 
                                     row[5], row[6], row[7], row[8], 
                                     row[9], row[10], row[11], row[12], 
                                     row[13], row[14], row[15]), 
                             tags='minus')
        cpt += 1
    self.treeplan.tag_configure('minus', background="#%02x%02x%02x" % (61, 72, 73), 
                                foreground="red")

这是样式:

    self.style = ttk.Style(master)
    self.style.theme_use("clam")
    self.style.configure("mystyle.Treeview", bd=0, background="black", 
                          foreground="white", fieldbackground="red")
    self.style.configure("mystyle.Treeview.Heading", font=('Calibri', 9,
                          'bold'), background="#383838", foreground="white")
    self.style.layout("mystyle.Treeview", [('mystyle.Treeview.treearea', 
                      {'sticky': 'news'})])

我实际上想将所有 Treeview 项目的背景设置为 "#%02x%02x%02x" % (61, 72, 73)

**编辑:

我正在使用 Treeview 添加部分代码:

self.treeplan_frame = Frame(master, background=rgbcon2((39, 46, 46)))
self.treeplan_frame.grid(row=7, column=0, columnspan=8, sticky="nws", pady=10, padx=10)
self.treeplan = ttk.Treeview(self.treeplan_frame, height=19, style="mystyle.Treeview")

如您所见,我尝试使用 Style 更改背景但没有运气。 然后我尝试通过配置标签(标签/标签)来改变。 我检查了不同的线程,我不太清楚为什么在这种情况下它不起作用。 顺便提一句。 我是 Python 3.7 和 Tkinter 8.6。 当我有 3.6 时,我没有任何问题,而且以前版本的 Tkinter(我不确定是哪一个)。

解决方案位于: https : //bugs.python.org/issue36468

根据链接,问题出在 Tkinter 版本上。 人们认为问题出在 Python 版本上,但那是因为 Python 版本使用了有问题的 Tkinter 版本。

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

我很确定 'tags' 关键字必须得到一个元组而不是一个字符串,要强制转换,只需写成像 ('minus',) 这样的 'minus' 。

编辑:文档实际上说“标签”关键字实际上应该得到一个列表,但我已经看到很多提供元组的例子。 我想这是因为元组可以解析为列表。

暂无
暂无

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

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