Python| Kivy 中的按钮操作
Kivy 是Python中一个独立于平台的 GUI 工具。因为它可以在Android、IOS、Linux和Windows等平台上运行。它基本上是用来开发Android应用程序的,但这并不意味着它不能在桌面应用程序上使用。
???????? Kivy Tutorial – Learn Kivy with Examples.
现在在本文中,我们将学习如何使用kv 文件在 kivy 中构建一个按钮,就像我们在计算器和更多地方使用的按钮一样。
纽扣 :
Button 是一个具有关联操作的标签,这些操作在按下按钮时触发(或在单击/触摸后释放)。要绑定按钮按下时的动作,我们有函数on_press 。
使用 .kv 文件的按钮操作的基本方法:
1) Import kivy
2) Import kivy app
3) Import Box layout
4) create .kv with label and button
5) Bind button to a method
6) create method
现在让我们编写 .py 文件。
Python3
# import kivy module
import kivy
# this restrict the kivy version i.e
# below this kivy version you cannot
# use the app or software
kivy.require("1.9.1")
# base Class of your App inherits from the App class.
# app:always refers to the instance of your application
from kivy.app import App
# BoxLayout arranges children
# in a vertical or horizontal box.
from kivy.uix.boxlayout import BoxLayout
# class in which we are defining action on click
class RootWidget(BoxLayout):
def btn_clk(self):
self.lbl.text = "You have been pressed"
# creating action class and calling
# Rootwidget by returning it
class ActionApp(App):
def build(self):
return RootWidget()
# creating the myApp root for ActionApp() class
myApp = ActionApp()
# run function runs the whole program
# i.e run() method which calls the
# target function passed to the constructor.
myApp.run()
Python3
# Base widget from Rootwidget class in .py file
:
# used to change the label text
# as in rootwidget class
lbl:my_label
# child that is an instance of the BoxLayout
BoxLayout:
orientation: 'vertical'
size: [1, .25]
Button:
text:'Click Me'
font_size:"50sp"
color: [0, 255, 255, .67]
on_press: root.btn_clk()
Label:
# id is limited in scope to the rule
# it is declared in. An id is a weakref
# to the widget and not the widget itself.
id: my_label
text: 'No click Yet'
color: [0, 84, 80, 19]
上述代码的 .kv 文件 [action.kv] :
必须与 ActionApp 类的名称一起保存。即action.kv。
Python3
# Base widget from Rootwidget class in .py file
:
# used to change the label text
# as in rootwidget class
lbl:my_label
# child that is an instance of the BoxLayout
BoxLayout:
orientation: 'vertical'
size: [1, .25]
Button:
text:'Click Me'
font_size:"50sp"
color: [0, 255, 255, .67]
on_press: root.btn_clk()
Label:
# id is limited in scope to the rule
# it is declared in. An id is a weakref
# to the widget and not the widget itself.
id: my_label
text: 'No click Yet'
color: [0, 84, 80, 19]
输出:
视频解释输出:
注意: BoxLayout 以一个在另一个之上的垂直方式或以一个接一个的水平方式排列小部件。