Kivy Chinese Tutorial Instance Getting Started Simple Paint App: 1. Custom widget (widget)



1. Framework code Create a new project named SimplePaintApp

with PyCharm, and then create a new PYTHON source file named simple_paint_app.py.

In the code editor, enter the following framework code

 

   1 from kivy.app import App

2 from kivy.uix. widget import Widget





5 class MyPaintWidget(Widget):

6 pass





9 class MyPaintApp(App):

10 def build(self):

11 return MyPaintWidget()

12 

13 

14 if __name__ == '__main__':

15 MyPaintApp() .run()

 

runs the above code and will display a window with a black background. It

 

looks boring, but don't underestimate these lines of code. These are the framework codes of Simple Sketchpad, which is like the skeleton of the program. Later, Dr. Mi will lead you to add various new functions to this skeleton, and gradually enrich and improve the application.

Line 5 class MyPaintWidget(Widget): Inheriting from class Widget to construct our custom widget MyPaintWidget. The main logic of the artboard will be implemented in the MyPaintWidget class. Now we only write a pass (line 6), which is equivalent to a placeholder. Let the entire code run first. We will add the specific functions in the following tutorials.

Line 12 return MyPaintWidget() creates and returns the custom widget object MyPaintWidget when the app is initialized (calling the build method)

2. Adding Interaction

Now that our custom widget can't do anything, let's try to make it responsive User action.

The code is as follows:

 

   1 from kivy.app import App

2 from kivy.uix.widget import Widget





5 class MyPaintWidget(Widget):

6 def on_touch_down(self, touch):

7 print(touch)





10 class MyPaintApp(App) :

11 def build(self):

12 return MyPaintWidget()

13 

14 

15 if __name__ == '__main__':

16 MyPaintApp().run()

 

runs the modified code and still displays a black window, which doesn't seem to have changed. However, when you click in the window with the mouse, you will find that there is output in the PyCharm console, and the output number will change with the click position.

 

MyPaintWidget's on_touch_down method (line 6) is triggered when the user clicks with the mouse on the window. The touch parameter of the on_touch_down method contains the position information when the mouse is clicked. Here, we haven't implemented any useful interaction, just output the position information of the mouse click to the console, that is, the 7th line of code print(touch)

[Thinking]

Use the application in this section as an experiment, thinking that the coordinate system used by kivy is how is it like? (Where is the origin? What is the direction of x and y?)

Original link: http://www.ipaomi.com/2017/11/15/kivy-Chinese Tutorial-Introduction to Examples-Simple Sketchpad-simple-paint-app: 1 - custom window section /

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326390461&siteId=291194637