python代码如下:
import kivy
kivy.require('2.0.0')
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import ObjectProperty, StringProperty
class Controller(FloatLayout):
label_wid = ObjectProperty
info = StringProperty
def do_action(self):
self.label_wid.text = 'button pressed'
self.info = 'bye'
class yo24App(App):
def build(self):
return Controller(info = 'hello world')
if __name__=='__main__':
yo24App().run()
kivy代码如下(存为yo24.kv):
<Controller>:
label_wid:my_custom_label
BoxLayOut:
orientation:'horizontal'
padding:20
Button:
text:'MY controller info is:'+root.info
on_press:root.do_action()
label:
id:my_custom_label
text:'my label before button press'
运行python文件的时候总是有typeerro,请问,谁知道我错在哪了么?谢谢!
啊这,兄弟,又碰见你了,学了一晚上kivy吗。
我估摸着你可能是照着哪个网上的代码魔改来着,然而要魔改全呀兄弟。
这里class yo24(FloatLayOut), class yo24App(App), yo24.kv, <yo24>:都要保持一致的。你可能把Controller看做是个单独的部件,其实这也是自己规定的继承自FloatLayout布局的类。
这样修改即可:
import kivy
kivy.require('1.8.0')
from kivy.uix.floatlayout import FloatLayout
from kivy.app import App
from kivy.properties import ObjectProperty, StringProperty
class yo24(FloatLayout):
label_wid = ObjectProperty()
info = StringProperty()
def do_action(self):
self.label_wid.text = 'button pressed'
self.info = 'bye'
class yo24App(App):
def build(self):
return yo24(info='hello world')
if __name__ == '__main__':
yo24App().run()
这段代码保存的名称无所谓。
下面的文件保存为yo24.kv。
<yo24>:
label_wid: my_custom_label
BoxLayout:
orientation: 'horizontal'
padding: 20
Button:
text: 'MY controller info is: ' + root.info + '\n'
on_press: root.do_action()
Label:
id: my_custom_label
text: 'my label before button press'
此外还有许多大小写的问题都有可能导致BUG,题主自己比对一下吧。
========================================本机执行无误。
import kivy kivy.require('2.0.0') from kivy.uix.floatlayout import FloatLayout from kivy.app import App from kivy.properties import ObjectProperty, StringProperty class controller(FloatLayout): label_wid = ObjectProperty() info = StringProperty() def do_action(self): self.label_wid.text = 'button pressed' self.info = 'bye' class yo24App(App): def build(self): return controller(info='hello world') if __name__ == '__main__': yo24App().run()
下面是kv文件,存储为yo24.kv
<controller>: label_wid: my_custom_label BoxLayout: orientation: 'horizontal' padding: 20 Button: text: 'MY controller info is: ' + root.info + '\n' on_press: root.do_action() Label: id: my_custom_label text: 'my label before button press'
感谢profsnail不耐其烦的帮忙解决这个问题。虽然不是profsnail所说的,必须要将所有的名称统一,但非常感谢他帮忙重新编译了代码。很可能错误存在与缩进或者大小写方面。谢谢!
把正确的代码和错误的代码仔仔细细的看了n遍,终于知道
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
翻译:类型错误:object.__init__() 至少需要一个参数(实例初始化)
这个类型错误为什么会出现了!
label_wid = ObjectProperty info = StringProperty
这两句就是错误产生的原因,原来是属性也是需要一个参数的,哪怕是空的,也要有个(),因此修改如下就搞定:
label_wid = ObjectProperty() info = StringProperty()
比对代码可以不用肉眼一个一个盯着看,https://www.matools.com/compare