Python|在 kivy 中创建一个简单的绘图应用程序
Kivy 是Python中一个独立于平台的 GUI 工具。因为它可以在Android、IOS、Linux和Windows等平台上运行。它基本上是用来开发Android应用程序的,但这并不意味着它不能在桌面应用程序上使用。
Kivy Tutorial – Learn Kivy with Examples.
绘图应用程序:
在这里,我们将在 kivy 的帮助下创建一个简单的绘图应用程序,最初我们只是制作一个画布和一个画笔,以便通过移动光标您可以感觉像一个绘图应用程序。
在此,小部件是动态添加的。如果要在运行时动态添加小部件,则取决于用户交互,它们只能添加到Python文件中。
我们正在使用小部件、布局、随机来使其变得更好。
Now Basic Approach of the App:
1) import kivy
2) import kivy App
3) import Relativelayout
4) import widget
5) set minimum version(optional)
6) Create widget class as needed
7) Create Layout class
8) create the App class
9) create .kv file
10) return the widget/layout etc class
11) Run an instance of the class
守则的实施:
# .py 文件:
Python3
# Program to explain how to create drawing App 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
kivy.require('1.9.0')
# Widgets are elements of a
# graphical user interface that
# form part of the User Experience.
from kivy.uix.widget import Widget
# This layout allows you to set relative coordinates for children.
from kivy.uix.relativelayout import RelativeLayout
# Create the Widget class
class Paint_brush(Widget):
pass
# Create the layout class
# where you are defining the working of
# Paint_brush() class
class Drawing(RelativeLayout):
# On mouse press how Paint_brush behave
def on_touch_down(self, touch):
pb = Paint_brush()
pb.center = touch.pos
self.add_widget(pb)
# On mouse movement how Paint_brush behave
def on_touch_move(self, touch):
pb = Paint_brush()
pb.center = touch.pos
self.add_widget(pb)
# Create the App class
class DrawingApp(App):
def build(self):
return Drawing()
DrawingApp().run()
Python3
# Drawing.kv implementation
# for assigning random color to the brush
#:import rnd random
# Paint brush coding
:
size_hint: None, None
size: 25, 50
canvas:
Color:
rgb: rnd.random(), rnd.random(), rnd.random()
Triangle:
points:
(self.x, self.y, self.x + self.width / 4, self.y,
self.x + self.width / 4, self.y + self.height / 4)
# Drawing pad creation
:
canvas:
Color:
rgb: .2, .5, .5
Rectangle:
size: root.size
pos: root.pos
# .ky 文件:
Python3
# Drawing.kv implementation
# for assigning random color to the brush
#:import rnd random
# Paint brush coding
:
size_hint: None, None
size: 25, 50
canvas:
Color:
rgb: rnd.random(), rnd.random(), rnd.random()
Triangle:
points:
(self.x, self.y, self.x + self.width / 4, self.y,
self.x + self.width / 4, self.y + self.height / 4)
# Drawing pad creation
:
canvas:
Color:
rgb: .2, .5, .5
Rectangle:
size: root.size
pos: root.pos
输出: