python-23-手机APP应用举例

Kivy总体思想是:kv代码管界面,python代码管逻辑。

在Python中的代码中经常会见到这两个词 args 和 kwargs,前面通常还会加上一个或者两个星号。其实这只是编程人员约定的变量名字,args 是 arguments 的缩写,表示位置参数;kwargs 是 keyword arguments 的缩写,表示关键字参数。这其实就是 Python 中可变参数的两种形式,并且 *args 必须放在 **kwargs 的前面,因为位置参数在关键字参数的前面。

1 hello world

1.1 纯python文件

文件main.py

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

class IndexPage(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.btn = Button(text = "helloworld")
        self.add_widget(self.btn)

class TestApp(App):
    def build(self):
        return IndexPage()

if __name__ == "__main__":
    TestApp().run()

1.2 python文件和.kv文件

将下面的两行代码替换掉
self.btn = Button(text = “helloworld”)
self.add_widget(self.btn)

文件test.kv

<IndexPage>:
    Button:
        text: "helloworld"

文件main.py

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

class IndexPage(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)

class TestApp(App):
    def build(self):
        return IndexPage()

if __name__ == "__main__":
    TestApp().run()

2 button按钮事件

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

class IndexPage(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.btn = Button(text = "press me")
        self.btn.bind(on_press = self.press_button)
        self.add_widget(self.btn)

    def press_button(self, arg):
        print("press button is running")
        
class TestApp(App):
    def build(self):
        return IndexPage()

if __name__ == "__main__":
    TestApp().run()

3 Label标签

下载字体支持中文

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

class IndexPage(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        # Button按钮
        self.btn = Button(text = "press me")
        self.btn.bind(on_press = self.press_button)
        self.add_widget(self.btn)
        # Label标签
        self.la = Label(font_name = "./arialuni.ttf")
        self.add_widget(self.la)
    def press_button(self, arg):
        self.la.text = "show you看"

class TestApp(App):
    def build(self):
        return IndexPage()

if __name__ == "__main__":
    TestApp().run()

猜你喜欢

转载自blog.csdn.net/qq_20466211/article/details/113794117