控件Widget是 Kivy 圖形界面中的基本元素搏色。控件提供了一個(gè)畫布Canvas明垢。
layout = BoxLayout(padding=10)
button = Button(text='My first button')
layout.add_widget(button)
layout 是button的父控件
button是layout的子控件
嘗試創(chuàng)建控件
class MyVideoBox(Widget):
? ? def __init__(self, **kwargs):
? ? ? ? super(MyVideoBox, self).__init__(**kwargs)
? ? ? ? with self.canvas:
? ? ? ? ? ? print self.x,self.y,self.width,self.height
加入到GridLayout蚣常,放到第四格的位置
class MainScreen(GridLayout):
? ? def __init__(self,**kwargs):
? ? ? ? super(MainScreen,self).__init__(**kwargs)
? ? ? ? self.cols = 2
? ? ? ? self.add_widget(Button(text="+"));
? ? ? ? self.add_widget(Button(text="+"));
? ? ? ? self.add_widget(Button(text="+"));
? ? ? ? #self.add_widget(Button(text="+"));
? ? ? ? self.add_widget(MyVideoBox())
但是效果是放在左下,而不是layout第四格的位置
打印是0 0 100 100
有點(diǎn)奇怪痊银,為什么不是相對位置呢?
修改一下
self.add_widget(MyVideoBox(pos=(800,0),size=(800,600)))
這下對了
打印是800 0 800 600
接下來為這個(gè)widget添加紋理
with self.canvas:
? ? print self.x,self.y,self.width, self.height
? ? self._texture = Texture.create(size=self.size)
? ? self._buffer = '\xf0\x20\x80' * 800 * 600
? ? self._texture.blit_buffer(self._buffer, colorfmt='rgb', bufferfmt='ubyte')
? ? Rectangle(pos=self.pos,size=self.size,texture=self._texture)
但是更新內(nèi)容測試一下抵蚊,添加按鍵
def on_touch_down(self, touch):
? ? print "touched"
? ? buf = '\x20\xf0\x80' * 800 * 600
? ? self._texture.blit_buffer(buf, colorfmt='rgb', bufferfmt='ubyte')
? ? return super(MyVideoBox, self).on_touch_down(touch)
打印有了,就是內(nèi)容沒變,怎么辦贞绳?
改變?nèi)缦?/p>
? ? self._texture.blit_buffer(buf, colorfmt='rgb', bufferfmt='ubyte')
self.canvas.ask_update()
成功
問題: remove_widget 不起作用
def __init__(self, **kwargs):
? ? super(MyVideoBox, self).__init__(**kwargs)
with self.canvas:
self.add_widget(self._button)
def on_touch_down(self, touch):
self.remove_widget(self._button)
解決:
移到cavas外面
def __init__(self, **kwargs):
? ? super(MyVideoBox, self).__init__(**kwargs)
self.add_widget(self._button)
with self.canvas:
def on_touch_down(self, touch):
self.remove_widget(self._button)
這樣可以了