Kivy:如何将画布用于在python中创建的小部件 [英] Kivy: how to use canvas for widgets created in python

查看:122
本文介绍了Kivy:如何将画布用于在python中创建的小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在其复选框中添加一个画布以更改其颜色.我已经找到了这个答案,但是我正在努力实现它. 我的复选框使用以下代码在python中创建:

I would like to add a canvas to my checkboxes to change their color. I have found this answer, but I am struggling to implement it. My checkboxes are created in python with this code:

checkb= CheckBox()
layout.add_widget(checkb)

尝试1:我从这里,但未成功:

Attempt 1: I tried the solution from here but without success:

checkb= CheckBox()
checkb.canvas.add(Color(1., 1., 0))
checkb.canvas.add(Rectangle(size=(50, 50)))
layout.add_widget(checkb)

尝试2:我还尝试过在构建器中创建一个自定义复选框,但没有找到使其工作的方法(我找不到有关这种设置的任何信息,因此我不确定甚至有可能使其正常运行):

Attempt 2: I also tried to come up with a custom checkbox created in the builder but didn't find a way to make it work (I couldn't find any info about this kind of setup, so I am not sure it's even possible to make it work):

Builder.load_string('''
<CustomCk@CheckBox>:
    canvas.before:
        Color:
            rgb: 1,0,0
        Rectangle:
            pos:self.center_x-8, self.center_y-8
            size:[16,16]
        Color:
            rgb: 0,0,0
        Rectangle:
            pos:self.center_x-7, self.center_y-7
            size:[14,14]                

''')

checkb= CustomCk()
layout.add_widget(checkb)


我尝试使用with语句:


Edit : my try with the with statement:

checkb= CheckBox()  
with checkb.canvas:
    Color(1, 2, 0)
    Rectangle(size=(50, 50))
layout.add_widget(checkb)

推荐答案

您应该使用python代码中的 with 语句

You should use the with statement from your python code

with checkb.canvas:
    Color(1., 1., 0)
    Rectangle(size=(50, 50))

您的其他方法似乎更好,只需对其进行一些修复:

Your other approach seems better, just fix it a bit:

Builder.load_string('''
<CustomCk>:
    canvas.before:
        Color:
            rgb: 1,0,0
        Rectangle:
            pos:self.center_x-8, self.center_y-8
            size:[16,16]
        Color:
            rgb: 0,0,0
        Rectangle:
            pos:self.center_x-7, self.center_y-7
            size:[14,14]                

    ''')

class CustomCk(CheckBox): #define the class in the python file... 
     pass

checkb= CustomCk()
layout.add_widget(checkb)

这篇关于Kivy:如何将画布用于在python中创建的小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆