Skip to main content

Calculator using Pygame vs PySimpleGUI

                                    Pygame                                                                                 PySimpleGUI
             
        เนื่องจากเราได้รับมอบหมายให้ทำเครืองคิดเลขโดยการใช้ทั้ง Pygame และ PySimpleGUI จึงเขียนบล็อกนี้ให้เห็นถึงความแตกต่างของใช้งานของทั้งสอง library ซึ่งเราจะพูดถึงก่อน Pygame กันก่อน
        ก่อนจะสร้างเครื่องคิดเลขใน Pygame ได้ (ศึกษาคำสั่งต่าง ๆ ได้จาก pygame documentation)เราก็ต้องมาออกแบบฟังก์ชันพื้นฐานว่าต้องการอะไรในเครื่องคิดเลขของเราบ้าง(หน้าตาของเครื่องคิดเลข. ปุ่มกดต้องมีปุ่มอะไรบ้าง, ...) อันดับแรกเลย อ. อยากให้เราสร้าง class ของปุ่มกด ซึ่งเราก็ต้องกลับมาคิดว่าปุ่มกดของเราจะเป็นรูปทรงอะไร เราเลือกให้เป็นรูปสี่เหลี่ยมผืนผ้าง่ายๆ
        เริ่มต้นใช้งานต้องไม่ลืม 👉 import pygame 👈โดยคำสั่งในการสร้างสี่เหลี่ยมผืนผ้าและรูปทรงอื่น ๆ ของ Pygame จะใช้คำสั่ง pygame.draw โดยมีรูปทรงให้เลือกต่าง ๆ ดังนี้
               pygame.draw.rect — draw a rectangle shape
               pygame.draw.polygon — draw a shape with any number of sides
               pygame.draw.circle — draw a circle around a point
               pygame.draw.ellipse — draw a round shape inside a rectangle
               pygame.draw.arc — draw a partial section of an ellipse
               pygame.draw.line — draw a straight line segment
               pygame.draw.lines — draw multiple contiguous line segments
               pygame.draw.aaline — draw fine antialiased lines
               pygame.draw.aalines — draw a connected sequence of antialiased lines
        โดยที่คำสั่ง  pygame.draw.rect จะต้องใส่ค่าในวงเล็บดังนี้ (Surface, color, Rect, width=0) เราจึงสร้างคลาสที่ต้องใส่ surface ที่จะสร้างสี่เหลี่ยม, สี, ตำแหน่งใน surface และ ขนาดของสี่เหลี่ยม โดยมี class method สำหรับ set color และ วาดสี่เหลี่ยม
 class Button():  
   def __init__(self, screen, color, x ,y ,w, h):  
     self.screen = screen  
     self.color = color  
     self.x = x  
     self.y = y  
     self.w = w  
     self.h = h  
   def color(self, color):  
     self.color = color  
     return self.Rect()  
   def Rect(self):  
     return pygame.draw.rect(self.screen, self.color, (self.x, self.y, self.w, self.h))  
        แล้วเราก็ได้สร้าง class สำหรับการดำเนินการในการรับค่าจากปุ่มต่าง ๆ ดังนี้
 class Function():  
   def __init__(self):  
     self.output = []  
   def __len__(self):  
     if len((self.output)) > 30: #limit len(output) = 30  
       self.output = self.output[:-1]  
     return len(self.output)  
   def is_empty(self):  
     return len(self.output) == 0  
   def push(self, e):  
     self.output.append(e)  
     print(self.output)  
   def pop(self):  
     try:  
       self.output = self.output[:-1]  
     except IndexError:  
       pass  
   def remove(self):  
     return self.output.clear()  
   def sum_list(self):  
     return ''.join(self.output)  
        ต่อไปจะเป็นการสร้างหน้าต่างของเครื่องคิดเลข ซึงเราออกแบบให้เป็น grid ขนาด 100x60 มี margin = 2 ทั่ว surface แล้ววาดสี่เหลี่ยมลงใน grid เพื่อให้เป็นปุ่ม (ศึกษาได้จาก Introduction to computer science using python and pygame)
        module ที่ใช้ในส่วนนี้หลัก ๆ จะมี
               pygame.init — สำหรับ initialize ทุก module ใน pygame
               pygame.display — สำหรับควบคุม display window และ screen
               pygame.Surface — สำหรับแสดงวัตถุต่าง ๆ
               pygame.font — สำหรับตั้งค่า font และใส่ font ใน display
               pygame.mouse — สำหรับรับคำสั่งจาก mouse
               pygame.key — สำหรับรับคำสั่งจาก keyboard
               pygame.quit — สำหรับ uninitialize ทุก module ใน pygame 
ดู code เพิ่มเติมได้ที่ https://github.com/Manachanok/Calculator/blob/master/CALCULATOR.py

ตัวอย่างการใช้งานเครื่องคิดเลขที่สร้างจาก Pygame

        ต่อไปเป็นการสร้างเครื่องคิดเลขจาก library PySimpleGUI ก่อนจะใช้งานก็ต้อง install package เหมือนกันกับ Pygame ก่อน ซึ่ง PySimpleGUI ก็คือ library สำหรับสร้าง GUI:Graphical User Interface ใน python โดยมีพื้นฐานมาจาก tkinter ซึ่งให้ผู้ใช้สามารถใช้งานได้ง่ายขึ้น
        แต่ว่าข้อมูลวิธีการใช้งาน PySimpleGUI จากแหล่งอื่น ๆ มีค่อนข้างน้อย ส่วนใหญ่ในสามารถดูได้จาก Docs และ The PySimpleGUI Cookbook ซึ่งเราเองก็ดูตัวอย่างจาก Keypad Touchscreen Entry - Input Element Update เพื่อมาปรับใช้กับเครื่องคิดเลขของเรา ตาม code ด้านล่างนี้
 import PySimpleGUI as sg  
 layout = [  
      [sg.Input(size=(45, 1), do_not_clear=True, justification='right', key='input')],  
      [sg.Text('Ans :', size=(14, 1), font=('Segoe UI', 13), text_color='gray')],[sg.Text('', size=(14, 1), font=('Segoe UI', 18), text_color='black', key='out')],  
      [sg.ReadFormButton('(', button_color=('black', 'white')), sg.ReadFormButton(')', button_color=('black', 'white')), sg.ReadFormButton('del', button_color=('black', 'white')), sg.ReadFormButton('C', button_color=('black', 'white'))],  
      [sg.ReadFormButton('7', button_color=('black', 'orange')), sg.ReadFormButton('8', button_color=('black', 'orange')), sg.ReadFormButton('9', button_color=('black', 'orange')), sg.ReadFormButton('/', button_color=('black', 'white'))],  
      [sg.ReadFormButton('4', button_color=('black', 'orange')), sg.ReadFormButton('5', button_color=('black', 'orange')), sg.ReadFormButton('6', button_color=('black', 'orange')), sg.ReadFormButton('*', button_color=('black', 'white'))],  
      [sg.ReadFormButton('1', button_color=('black', 'orange')), sg.ReadFormButton('2', button_color=('black', 'orange')), sg.ReadFormButton('3', button_color=('black', 'orange')), sg.ReadFormButton('-', button_color=('black', 'white'))],  
      [sg.ReadFormButton('.', button_color=('black', 'white')), sg.ReadFormButton('0', button_color=('black', 'orange')), sg.ReadFormButton('=', button_color=('black', 'white')), sg.ReadFormButton('+', button_color=('black', 'white'))],  
      ]  
 form = sg.FlexForm('Calculator', default_button_element_size=(8, 2), auto_size_buttons=False, grab_anywhere=False)  
 form.Layout(layout)  
               sg.Input — สำหรับตั้งค่ารูปแบบตัวอักษรที่ input
               sg.Text — สำหรับตั้งค่าตัวอักษร(ตัวอักษรที่จะแสดง, ขนาด,  font, สี)
               sg.ReadFormButton — สำหรับแทนค่าแต่ละปุ่มกดด้วยตัวอักษรต่าง ๆ
               sg.FlexForm — สำหรับตั้งค่า title, ขนาดปุ่มกด
 # Loop forever reading the form's values, updating the Input field  
 keys_entered = ''  
 while True:  
   button, values = form.Read() # read the form  
   try:  
     if button is '=':  
       keys_entered = values['input']  
       sum = eval(keys_entered)  
       form.FindElement('out').Update(sum)  
   except ZeroDivisionError:  
     form.FindElement('out').Update('Error')  
   except SyntaxError:  
     form.FindElement('out').Update('Error')  
   if button is None: # if the X button clicked, just exit  
      break  
   if button is 'C': # clear keys if clear button  
     keys_entered = ''  
   elif button is 'del':  
     keys_entered = values['input']  
     keys_entered = keys_entered[:-1]  
   elif button in '()1234567890./*-+':  
     keys_entered = values['input'] # get what's been entered so far  
     keys_entered += button # add the new digit  
    # output the final string  
   form.FindElement('input').Update(keys_entered) # change the form to reflect current key string  
        ส่วนนี้จะเป็นส่วนของการดำเนินการภายในเครื่องคิดเลข เช่น การรับค่าจะปุ่มกดแล้วแสดงผลในช่อง input, การรวมผลลัพธ์, การแสดงผลลัพธ์ที่ได้, การแก้ไข error ที่เกิดขึ้น เป็นต้น

ตัวอย่างการใช้งานเครื่องคิดเลขที่สร้างจาก PySimpleGUI


        ความแตกต่างของ Pygame และ PySimpleGUI คือ PySimpleGUI ใช้งานง่ายกว่ามาก ๆ ทำให้สร้างเครื่องคิดเลขออกมาได้เร็วกว่ามาก ๆ 👍 แต่ว่ารูปทรงของปุ่มกด สี และอื่น ๆ นั้น Pygame ทำได้หลากหลายกว่ามาก ๆ 💖
        ดังนั้นการเลือกใช้งานอาจจะต้องเลือกตามความต้องการของตัวเองว่าต้องการใช้เครื่องคิดเลขของตัวเองออกมาแบบไหนนั่นเอง





Comments

Popular posts from this blog

A running light using TinkerCad's Circuits

Tinkercad is a free online collection of software tools for help people all over the world think, create and make. We're the ideal introduction to Autodesk, the leader in 3D desigm, engineering and entertainment software. Tinkercad        พูดสั้น ๆ ก็คือ Tinkercad เป็น online software ที่ช่วยออกแบบงานในรูปแบบเสมือนจริง ซึ่งงานเราจะใช้ Tinkercad ในการออกแบบไฟกะพริบกัน และเนื่องจากเป็นครั้งแรกที่ได้ทดลองใช้ Arduino program เพื่อสร้าง block สำหรับ 8-bit LED ที่ LED จะกะพริบจากซ้ายไปขวา จึงไปหาข้อมูลวิธีการใช้งานจนมาเจอ Channel ที่ชื่อ Autodesk Tikercad ใน Youtube ซึ่ง ส อนต่อวงจรที่ลักษณะคล้ายกับวงจรที่ต้องกา ร        สามารถทำได้ดังนี้        เลือก Sign in(สำหรับคนที่มี account อยู่แล้ว) หรือ Join now(สำหรับคนที่ยังไม่มี account ของ Tinkercad)         เลือก Circiut ทางซ้ายมือ แล้วเลือก Create new Circuit        เลือก Components จากทางขวา โดยต่อสายไฟเข้ากับช่อง 5V ของ Arduino และ แถว red (+) power ใน board แล้วต่อ GND เข้ากับ black (-) power        วางให้ขาขอ

What is Pygame and how to install?

Pygame ก็คือ library ที่ใช้สำหรับสร้าง multimedia application อย่างเช่น game ในภาษา Python นั่นเอง ซึ่งเกิดจากการพัฒนาต่อมาจาก PySDL(เป็นการนำ Python มารวมกับ SDL) ในเดือนตุลาคม ปี ค.ศ.2000 ก่อนจะใช้งาน Pygame เราจะต้องมี Python3.6 หรือสูงกว่านั้นก่อน กรณีที่ใช้ Window OS จะใช้การติดตั้งผ่าน command prompt โดยมีขั้นตอนดังนี้ Windows installation steps py - m pip install - U pygame -- user py - m pygame . examples . aliens โดยจะมีการแสดงผลตามรูป ถ้าหาก Pygame compile แล้วเกิด fail ให้ลอง upgrade pip ก่อน แต่ว่าเราใช้ Pygame ใน Pycharm ก็ต้องเข้าไป install package Pygame ใน Settings ก่อน ถ้ายังไม่มี package pygame ให้เลือกที่เครื่องหมาย "+" ทางขวามือ แล้ว search pygame แล้ว install package แค่นี้เราก็สามารถใช้ Pygame ใน Pycharm ได้แล้ว 🎉