6

Kivy 2.0的一个变化

 3 years ago
source link: https://segmentfault.com/a/1190000040401071
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Kivy 2.0的一个变化

发布于 今天 14:29

Kivy支持完全使用代码创建界面布局和控件,最近也刚刚推出2.0版。使用的时候,发现新版跟旧版有一处差异:

import kivy
kivy.require('2.0.0') # replace with your current kivy version !

from kivy.app import App
from kivy.uix.label import Label


class MyApp(App):

    def build(self):
        label = Label(id='mouse_label',
                            text='pos~~~',
                            pos=(0, 0),
                            width='50dp',
                            height='20dp',
                            font_size=12,
                            bold=True,
                            color=(0.1, 0.1, 0.1, 1),
                            outline_width=1,
                            outline_color=(1, 1, 1)
                            )
        return label


if __name__ == '__main__':
    MyApp().run()

上面把官网文档的示例代码稍作改动,增加了初始化Label的很多属性,在1.x版本中可以正常运行。但升级到2.0版,就会报错:

TypeError: object.__init__() takes exactly one argument (the instance to initialize)

这是个经典的Kivy报错,也非常诡异,完全不能理解——明明Label类的构造函数,可以接收多个参数么!即使调试进去,也看不出问题所在,只知道是调用父类的父类的(没看错,就是两级父类,指向WidgetBase)构造函数出错的。不过既然实例代码能用,问题肯定出在我补充的参数上,本来以为是哪个样式被废弃了,结果试来试去,发现竟然是id !?

只要把id='mouse_label'这行删掉,一切就恢复正常了,为什么暂时还不知。最终成功运行的代码如下:

import kivy
kivy.require('2.0.0') # replace with your current kivy version !

from kivy.app import App
from kivy.uix.label import Label


class MyApp(App):

    def build(self):
        label = Label(
                            text='pos~~~',
                            pos=(0, 0),
                            width='50dp',
                            height='20dp',
                            font_size=12,
                            bold=True,
                            color=(0.1, 0.1, 0.1, 1),
                            outline_width=1,
                            outline_color=(1, 1, 1)
                            )
        return label


if __name__ == '__main__':
    MyApp().run()

运行效果

image.png


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK