Dan*_*nno 1 python button python-2.7 kivy
我正在尝试使用一些自定义小部件构建一个kivy应用程序.但是每当我尝试使用它们时,它们都不能使用我的布局.使用普通按钮:
import kivy
kivy.require('1.8.0')
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ListProperty
class RootWidget(Widget):pass
class myApp(App):
def build(self):
global rw
rw = RootWidget()
return rw
if __name__ == '__main__':
myApp().run()
#:kivy 1.8.0
<RootWidget>:
BoxLayout:
size: root.size
orientation: 'horizontal'
spacing: 10
padding: 10
Button:
id: abut
text: "Custom Button"
Run Code Online (Sandbox Code Playgroud)
这按预期工作,我的Button基本上占用了整个窗口.但是当我尝试用我的自定义按钮替换Button时
import kivy
kivy.require('1.8.0')
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ListProperty
class MyWidget(Widget):
pressed = ListProperty([0, 0])
def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
self.pressed = touch.pos
return True
return super(MyWidget, self).on_touch_down(touch)
def on_pressed(self, instance, pos):
print ('pressed at {pos}'.format(pos=pos))
class RootWidget(Widget):pass
class someApp(App):
def build(self):
global rw
rw = RootWidget()
return rw
if __name__ == '__main__':
someApp().run()
#:kivy 1.8.0
<MyWidget>:
BoxLayout:
orientation: 'horizontal'
spacing: 10
Button:
id: abut
text: "Custom Button"
<RootWidget>:
BoxLayout:
size: root.size
orientation: 'horizontal'
spacing: 10
padding: 10
MyWidget:
Run Code Online (Sandbox Code Playgroud)
它只出现在窗口的左下角,并且不像按钮那样.我错过了什么?
此外,甚至有必要以这种方式创建自定义按钮吗?kivy教程使用这种方法来制作他们的自定义按钮,但我不能只做这样的事情
Button:
on_press: root.do_action()
Run Code Online (Sandbox Code Playgroud)
使每个按钮的行为不同?
您的实际问题是,虽然你MyWidget被放置在BoxLayout在KV文件,其子BoxLayout也不会有它的大小设置为MyWidget大小,因此只是保持默认的大小和位置(100, 100)在屏幕左下方的.
您可以通过在size: root.size规则中为其提供额外规则来解决此问题<RootWidget>,或者实际上通常使用BoxLayout(即子类BoxLayout代替Widget)更容易,这当然会为您提供免费的自动调整大小/定位.
另外,正如Joran所说,如果你只是想在按下按钮时做某事,你可以使用第二种方法...这就是你打算做的事情!我不知道你在看什么样的例子,但你通常不需要像你这样复杂的安排.
您可能还有兴趣知道,在最新版本(1.8)中,按钮行为已被抽象为一个ButtonBehavior处理检测触摸和调度on_press等的类.行为不是一个小部件,所以你可以将它与任何其他小部件一起子类化,使任何东西成为一个按钮!