問題描述
我想在我的復選框中添加一個畫布來更改它們的顏色.我找到了這個答案,但我正在努力實現它.我的復選框是使用以下代碼在 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 中創建的小部件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!