15. การประยุกต์ใช้แนวคิดเชิงวัตถุ

Object-Oriented Programming

15.1. จุดประสงค์

  • เขียนคำสั่งเพื่อใช้ชุดคำสั่งเสริมที่อิงแนวคิดเชิงวัตถุได้

15.2. Desktop Applications

ภาษา Python สามารถนำไปพัฒนาโปรแกรมบนเครื่องคอมพิวเตอร์ได้โดยสามารถเลือกใช้ชุดคำสั่งเสริมต่อไปนี้ได้

15.2.1. PyQt

qt5-01
 1import sys
 2from PyQt5.QtWidgets import QApplication, QWidget
 3from PyQt5.QtGui import QIcon
 4
 5
 6class Example(QWidget):
 7    
 8    def __init__(self):
 9        super().__init__()
10        
11        self.initUI()
12        
13        
14    def initUI(self):
15        
16        self.setGeometry(300, 300, 300, 220)
17        self.setWindowTitle('Icon')
18        self.setWindowIcon(QIcon('web.png'))        
19    
20        self.show()
21        
22        
23if __name__ == '__main__':
24    
25    app = QApplication(sys.argv)
26    ex = Example()
27    sys.exit(app.exec_())
../_images/qt5-01.png

15.2.2. Kivy

bounce
 1import kivy
 2kivy.require('1.0.7')
 3
 4from kivy.animation import Animation
 5from kivy.app import App
 6from kivy.uix.button import Button
 7
 8
 9class TestApp(App):
10
11    def animate(self, instance):
12        animation = Animation(pos=(100, 100), t='out_bounce')
13        animation += Animation(pos=(200, 100), t='out_bounce')
14        animation &= Animation(size=(500, 500))
15        animation += Animation(size=(100, 50))
16
17        animation.start(instance)
18
19    def build(self):
20        button = Button(size_hint=(None, None), text='plop', on_press=self.animate)
21        return button
22
23
24if __name__ == '__main__':
25    TestApp().run()
26
../_images/bounce.png

15.2.3. Pygame

camera
 1import pygame
 2import pygame.camera
 3from pygame.locals import *
 4
 5
 6class VideoCapturePlayer(object):
 7
 8    size = ( 640, 480 )
 9    def __init__(self, **argd):
10        self.__dict__.update(**argd)
11        super(VideoCapturePlayer, self).__init__(**argd)
12
13        self.display = pygame.display.set_mode( self.size, 0 )
14        self.init_cams(0)
15
16    def init_cams(self, which_cam_idx):
17        self.clist = pygame.camera.list_cameras()
18        #print (self.clist)
19
20        if not self.clist:
21            raise ValueError("Sorry, no cameras detected.")
22
23        try:
24            cam_id = self.clist[which_cam_idx]
25        except IndexError:
26            cam_id = self.clist[0]
27
28        self.camera = pygame.camera.Camera(cam_id, self.size, "RGB")
29        self.camera.start()
30        self.clock = pygame.time.Clock()
31        self.snapshot = pygame.surface.Surface(self.size, 0, self.display)
32
33    def get_and_flip(self):
34        if 0 and self.camera.query_image():
35            self.snapshot = self.camera.get_image(self.snapshot)
36        if 0:
37            self.snapshot = self.camera.get_image(self.snapshot)
38            self.display.blit(self.snapshot, (0,0))
39        else:
40            self.snapshot = self.camera.get_image(self.display)
41
42        pygame.display.flip()
43
44    def main(self):
45        going = True
46        while going:
47            events = pygame.event.get()
48            for e in events:
49                if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
50                    going = False
51                if e.type == KEYDOWN:
52                    if e.key in range(K_0, K_0+10) :
53                        self.init_cams(e.key - K_0)
54
55            self.get_and_flip()
56            self.clock.tick()
57            print (self.clock.get_fps())
58
59def main():
60    pygame.init()
61    pygame.camera.init()
62    VideoCapturePlayer().main()
63    pygame.quit()
64
65if __name__ == '__main__':
66    main()
67
../_images/camera.png

15.3. Mobile Applications

kitchensink
  1import ast
  2import os
  3import sys
  4
  5from kivy.lang import Builder
  6from kivy.factory import Factory
  7
  8from libs.baseclass.dialog_change_theme import KitchenSinkDialogChangeTheme
  9from libs.baseclass.list_items import KitchenSinkOneLineLeftIconItem
 10
 11from kivymd.app import MDApp
 12
 13if getattr(sys, "frozen", False):  # bundle mode with PyInstaller
 14    os.environ["KITCHEN_SINK_ROOT"] = sys._MEIPASS
 15else:
 16    sys.path.append(os.path.abspath(__file__).split("demos")[0])
 17    os.environ["KITCHEN_SINK_ROOT"] = os.path.dirname(os.path.abspath(__file__))
 18os.environ["KITCHEN_SINK_ASSETS"] = os.path.join(
 19    os.environ["KITCHEN_SINK_ROOT"], f"assets{os.sep}"
 20)
 21
 22
 23class KitchenSinkApp(MDApp):
 24    def __init__(self, **kwargs):
 25        super().__init__(**kwargs)
 26        self.theme_cls.primary_palette = "Teal"
 27        self.dialog_change_theme = None
 28        self.toolbar = None
 29        self.data_screens = {}
 30
 31    def build(self):
 32        Builder.load_file(
 33            f"{os.environ['KITCHEN_SINK_ROOT']}/libs/kv/list_items.kv"
 34        )
 35        Builder.load_file(
 36            f"{os.environ['KITCHEN_SINK_ROOT']}/libs/kv/dialog_change_theme.kv"
 37        )
 38        return Builder.load_file(
 39            f"{os.environ['KITCHEN_SINK_ROOT']}/libs/kv/start_screen.kv"
 40        )
 41
 42    def show_dialog_change_theme(self):
 43        if not self.dialog_change_theme:
 44            self.dialog_change_theme = KitchenSinkDialogChangeTheme()
 45            self.dialog_change_theme.set_list_colors_themes()
 46        self.dialog_change_theme.open()
 47
 48    def on_start(self):
 49        """Creates a list of items with examples on start screen."""
 50
 51        Builder.load_file(
 52            f"{os.environ['KITCHEN_SINK_ROOT']}/libs/kv/base_content.kv"
 53        )
 54        Builder.load_file(
 55            f"{os.environ['KITCHEN_SINK_ROOT']}/libs/kv/toolbar.kv"
 56        )
 57        with open(f"{os.getcwd()}/screens_data.json") as read_file:
 58            self.data_screens = ast.literal_eval(read_file.read())
 59
 60        for name_item_example in self.data_screens.keys():
 61            self.root.ids.backdrop_front_layer.data.append(
 62                {
 63                    "viewclass": "KitchenSinkOneLineLeftIconItem",
 64                    "text": name_item_example,
 65                    "icon": self.data_screens[name_item_example]["icon"],
 66                    "on_release": lambda x=name_item_example: self.set_example_screen(
 67                        x
 68                    ),
 69                }
 70            )
 71
 72    def set_example_screen(self, name_screen):
 73        manager = self.root.ids.screen_manager
 74        if not manager.has_screen(
 75            self.data_screens[name_screen]["name_screen"]
 76        ):
 77            name_kv_file = self.data_screens[name_screen]["kv_string"]
 78            Builder.load_file(
 79                f"{os.environ['KITCHEN_SINK_ROOT']}/libs/kv/{name_kv_file}.kv"
 80            )
 81            if "Import" in self.data_screens[name_screen]:
 82                exec(self.data_screens[name_screen]["Import"])
 83            screen_object = eval(self.data_screens[name_screen]["Factory"])
 84            self.data_screens[name_screen]["object"] = screen_object
 85            if "toolbar" in screen_object.ids:
 86                screen_object.ids.toolbar.title = name_screen
 87            manager.add_widget(screen_object)
 88        manager.current = self.data_screens[name_screen]["name_screen"]
 89
 90    def back_to_home_screen(self):
 91        self.root.ids.screen_manager.current = "home"
 92
 93    def callback_for_menu_items(self, *args):
 94        from kivymd.toast import toast
 95
 96        toast(args[0])
 97
 98    def show_demo_shrine(self, instance):
 99        """
100        :type instance <Screen name='shrine demo'> object
101
102        """
103
104        def add_screen_shrine(MDShrine):
105            def remove_box(*args):
106                instance.remove_widget(box)
107
108            from kivy.animation import Animation
109
110            md_shrine = MDShrine()
111            md_shrine.opacity = 0
112            instance.add_widget(md_shrine)
113
114            anim = Animation(opacity=0, d=0.5)
115            anim.bind(on_complete=remove_box)
116            anim.start(box)
117            Animation(opacity=2, d=0.5).start(md_shrine)
118            self.theme_cls.primary_palette = "Red"
119
120        def show_demo_shrine(interval):
121            from kivy.animation import Animation
122            from demos.kitchen_sink.studies.shrine.shrine import MDShrine
123
124            anim = Animation(
125                size_hint=(0.2, 0.2), pos_hint={"center_y": 0.7}, d=0.5
126            )
127            anim.bind(on_complete=lambda *x: add_screen_shrine(MDShrine))
128            anim.start(box)
129
130        from kivy.uix.boxlayout import BoxLayout
131        from kivy.metrics import dp
132        from kivy.uix.image import Image
133        from kivy.clock import Clock
134
135        box = BoxLayout(
136            orientation="vertical",
137            size_hint=(0.4, 0.6),
138            spacing=dp(10),
139            pos_hint={"center_x": 0.5, "center_y": 0.6},
140        )
141        path_to_logo = (
142            f"{os.environ['KITCHEN_SINK_ROOT']}/studies/shrine/data/images/shrine-white.png"
143            if self.theme_cls.theme_style == "Dark"
144            else f"{os.environ['KITCHEN_SINK_ROOT']}/studies/shrine/data/images/shrine-dark.png"
145        )
146        logo = Image(
147            source=path_to_logo, size_hint_x=0.8, pos_hint={"center_x": 0.5}
148        )
149        box.add_widget(logo)
150        box.add_widget(Factory.ShrinePresplashTile(text="SHRINE"))
151        instance.add_widget(box)
152        Clock.schedule_once(show_demo_shrine, 1)
153
154
155KitchenSinkApp().run()
156
../_images/kivyMD.png

15.4. Robot Applications

../_images/cozmo-promo.png

15.5. Web Applications

ชุดคำสั่งสำหรับพัฒนาเว็บไซต์สำหรับภาษา Python ที่สำคัญมีดังนี้

  1. django

  2. flask

  3. pyramid

  4. cherrypy

  5. web2py

15.5.1. Django

Laboratory

สร้างเว็บไซต์ส่วนตัวด้วย django บน https://pythonanywhere.com