Python Kivy .kv文件介绍和用法示例

2021年4月10日12:50:30 发表评论 1,581 次浏览

当我们用Python编写应用程序时基维, 在同一代码上编写所有内容会使代码混乱, 并且很难被别人理解。同样, 编写大型代码也难以维护窗口小部件树的构造和显式绑定的声明。

KV语言允许我们以声明的方式创建自己的窗口小部件树, 并以自然的方式将窗口小部件属性相互绑定或回调。

👉🏽Kivy教程–通过示例学习Kivy。

如何加载kv文件:

有2种方式加载.kv归档到代码或应用程序中

通过名称约定方法-

在编写代码时, 我们将创建App类。对于此方法, 文件名和应用程序类相同, 然后将kv文件保存为

appclassname.kv

Kivy会以小写形式查找与你的App类同名的Kv文件, 如果以" App"结尾则减去" App", 例如:

classnameApp ---> classname.kv

如果此文件定义了Root Widget, 它将被附加到应用程序的root属性, 并用作应用程序Widget树的基础。

下面给出了有关如何在kivy中使用.kv文件的示例代码:

# code how to use .kv file in kivy
  
# import kivy module
import kivy
  
# base Class of your App inherits from the App class.
# app:always refers to the instance of your application
from kivy.app import App
  
# this restrict the kivy version i.e
# below this kivy version you cannot 
# use the app or software
# not coumpulsary to write it
kivy.require( '1.9.1' )
  
# define the App class
# and just pass rest write on kvfile
# not necessary to pass
# can also define function in it
class kvfileApp(App):
     pass
  
kv = kvfileApp()
kv.run()

.kv文件代码以与应用程序类相同的名称保存–

Label:
     text:
         ( '[b]Hello[/b] [color = ff0099]World[/color]\n'
         '[color = ff0099]Hello[/color] [b]World[/b]\n'
         '[b]Hello[/b] [color = ff0099]World:):)[/color]' )
     markup: True
     font_size: '64pt'

输出如下:

Python | Kivy .kv文件1

生成器方法

为了使用此方法, 你首先必须通过以下方式导入Builder

from kivy.lang import builder

现在, 通过构建器, 你可以直接将整个文件作为字符串或文件加载。通过这样做将.kv文件加载为文件:

Builder.load_file('.kv/file/path')

或者, 对于加载, kv文件作为字符串:

Builder.load_string(kv_string)
# code to use the .kv file as a string in the main file
# code how to use .kv file in kivy
  
# import kivy module
import kivy
  
# base Class of your App inherits from the App class.
# app:always refers to the instance of your application
from kivy.app import App
  
# it is to import Builder
from kivy.lang import Builder
  
# this restrict the kivy version i.e
# below this kivy version you cannot use the app or software
# not coumpulsary to write it
kivy.require( '1.9.1' )
  
# building kv file as string
kvfile = Builder.load_string( """
Label:
     text:
         ('[b]Hello[/b] [color = ff0099]World[/color]\\n'
         '[color = ff0099]Hello[/color] [b]World[/b]\\n'
         '[b]Hello[/b] [color = ff0099]World:):)[/color]')
     markup: True
     font_size: '64pt'
""" )
  
# define the App class
# and just pass rest write on kvfile
# not necessary to pass
# can also define function in it
class kvfileApp(App):
     def build( self ):
         return kvfile
  
kv = kvfileApp()
kv.run()

输出如下:

Python | Kivy .kv文件2

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: