Simple painting App: 1. Custom widgets and kivywidgets
1. Framework Code
Use PyCharm to create a project named SimplePaintApp, and then create a 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 3 4 5 class MyPaintWidget(Widget): 6 pass 7 8 9 class MyPaintApp(App):10 def build(self):11 return MyPaintWidget()12 13 14 if __name__ == '__main__':15 MyPaintApp().run()
Run the above Code to display a black background window
It looks boring, but don't underestimate the lines of code. These are the Framework Code of the simple canvas, which is like the skeleton of a program. Dr. mi will guide you to add various new functions on this frame to enrich and improve applications.
Row 5th class MyPaintWidget (Widget): inherits from the class Widget to construct our custom Widget MyPaintWidget. The main logic of the canvas is implemented in the MyPaintWidget class. Now we only write one pass (6th rows), which is equivalent to a placeholder. Let's run the entire code segment first. We will add the specific functions in the following tutorial.
Row 12th return MyPaintWidget () is created when the application is initialized (the build method is called) and the custom widget object MyPaintWidget is returned.
2. Add Interaction
Now we can't do anything about custom Widgets. Next we will try to make them respond to user actions.
The Code is as follows:
1 from kivy.app import App 2 from kivy.uix.widget import Widget 3 4 5 class MyPaintWidget(Widget): 6 def on_touch_down(self, touch): 7 print(touch) 8 9 10 class MyPaintApp(App):11 def build(self):12 return MyPaintWidget()13 14 15 if __name__ == '__main__':16 MyPaintApp().run()
The modified code still displays a black window, which does not seem to have changed. However, when you click in the window with the mouse, you will find that there is an output in the PyCharm console, and the output numbers will change as the click position is different.
When you click in the window, the on_touch_down method of MyPaintWidget will be triggered (Row 3 ). The touch parameter of the on_touch_down method contains the location information when the mouse clicks. Here, we haven't implemented any useful interaction yet. We just output the cursor-clicked location information to the console, that is, print (touch) 7th lines of code)
[Thinking]
- Experiment with the application in this section and think about what kind of coordinate system is used by kivy? (Where is the origin? What is the direction of x and y ?)
Original article: Workshop/