首页 > 解决方案 > 如何在 kivy python 中更改树视图的背景颜色?

问题描述

我需要帮助来更改 kivy 上树视图的背景颜色。

我正在研究 python 中的 kivy 框架,它将列出一些标签。

但是在执行应用程序时会发生什么,我的应用程序背景颜色是白色,而树视图从应用程序背景中获取背景颜色。

下面是示例截图

在此处输入图像描述

示例代码: 创建树视图。

list_label=TreeView(root_options=dict(text='My root label'),hide_root=False)
list_label.add_node(TreeViewLabel(text='My first item'))

标签: pythonkivy

解决方案


将以下内容添加到您的.py:

Builder.load_string('''
<TreeView>:
    canvas.before:
        Color:
            rgba: 1, 0, 0, 1
        Rectangle:
            pos: self.pos
            size: self.size

''')

这会将背景更改为红色。您可以替换1, 0, 0, 1为您喜欢的任何颜色。

您可以完全在 中执行此操作Python,但您需要手动创建kv自动为您创建的绑定:

    list_label=TreeView(root_options=dict(text='My root label'),hide_root=False)

    with list_label.canvas.before:
        Color(1, 0, 0, 1)
        self.background_rect = Rectangle()
    list_label.bind(pos=self.adjust_rect_pos)
    list_label.bind(size=self.adjust_rect_size)

def adjust_rect_size(self, treeview, new_size):
    self.background_rect.size = new_size

def adjust_rect_pos(self, treeview, new_pos):
    self.background_rect.pos = new_pos

推荐阅读