不言而喻,我是kivy的新手,试图用三角形按钮编写一个简单的GUI(我希望它们不错,而不仅仅是仍然是从三角形部分点击的方形画布的图像)。所以我发现这个很棒的代码可以创建一个三角形并获得可点击区域。
基本上我只是希望它在按下时改变颜色(并在未按下时恢复)并且我太新了以至于无法使用它。
import kivy
from kivy.uix.behaviors.button import ButtonBehavior
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ListProperty
from kivy.vector import Vector
from kivy.lang import Builder
Builder.load_string('''
<TriangleButton>:
id: trianglething
# example for doing a triangle
# this will automatically recalculate pX from pos/size
#p1: 0, 0
#p2: self.width, 0
#p3: self.width / 2, self.height
# If you use a Widget instead of Scatter as base class, you need that:
p1: self.pos
p2: self.right, self.y
p3: self.center_x, self.top
# draw something
canvas:
Color:
rgba: self.triangle_down_color
Triangle:
points: self.p1 + self.p2 + self.p3
''')
def point_inside_polygon(x, y, poly):
'''Taken from http://www.ariel.com.au/a/python-point-int-poly.html
'''
n = len(poly)
inside = False
p1x = poly[0]
p1y = poly[1]
for i in range(0, n + 2, 2):
p2x = poly[i % n]
p2y = poly[(i + 1) % n]
if y > min(p1y, p2y):
if y <= max(p1y, p2y):
if x <= max(p1x, p2x):
if p1y != p2y:
xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x, p1y = p2x, p2y
return inside
class TriangleButton(ButtonBehavior, Widget):
triangle_down_color = ListProperty([1,1,1,1])
p1 = ListProperty([0, 0])
p2 = ListProperty([0, 0])
p3 = ListProperty([0, 0])
def changecolor(self, *args):
print "color"
self.ids.trianglething.canvas.triangle_down_color = (1,0,1,1)
def collide_point(self, x, y):
x, y = self.to_local(x, y)
return point_inside_polygon(x, y,
self.p1 + self.p2 + self.p3)
if __name__ == '__main__':
from kivy.base import runTouchApp
runTouchApp(TriangleButton(on_press=TriangleButton.changecolor,size_hint=(None,None)))
我在想这条线路错了:
self.ids.trianglething.canvas.triangle_down_color = (1,0,1,1)
但是我真的不知道。任何帮助将不胜感激
答案 0 :(得分:1)
您已经在小部件中,直接转到它,而不是通过ids
。 Ids
用于以kv语言在小部件的子级中设置的属性id
,例如如果您的TriangleButton有一个Image
的孩子id: myimage
,那么你可以得到它:
self.ids.myimage
因此,删除不必要的东西就足够了:
self.triangle_down_color = (1,0,1,1)
打印你真正想要的东西也很不错 - 如果它打印了一些物体,或者那个东西甚至不存在。并且绑定比手动放入on_press
:)
t = TriangleButton()
t.bind(on_press=function)