Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - การทำงานกับปุ่ม (Button) ใน Kivy

Kivy เป็น GUI toolkit อิสระแพลตฟอร์ม รันบน Android, iOS, Linux, Windows เขียนโค้ดครั้งเดียว ใช้ได้หลายแพลตฟอร์ม ใช้พัฒนาแอป Android เป็นหลัก แต่ใช้บน Desktop ได้เช่นกัน

Button เป็น Label พร้อมการกระทำเมื่อกด (หรือปล่อยหลังคลิก/แตะ) สามารถผูกฟังก์ชันและจัดสไตล์ได้

ตัวอย่าง: สร้างปุ่มพื้นฐาน

import kivy
kivy.require("1.9.1")

from kivy.app import App
from kivy.uix.button import Button

class ButtonApp(App):
    def build(self):
        btn = Button(
            text="Push Me!",
            font_size="20sp",
            background_color=(1, 1, 1, 1),
            color=(1, 1, 1, 1),
            size=(32, 32),
            size_hint=(.2, .2),
            pos=(300, 250)
        )
        btn.bind(on_press=self.callback)
        return btn

    def callback(self, event):
        print("button pressed")
        print('Kivy!')

if __name__ == '__main__':
    ButtonApp().run()

คำอธิบาย

  • kivy.require ระบุเวอร์ชันขั้นต่ำ
  • คลาส App ต้อง override build() คืนค่า root widget
  • Button พารามิเตอร์: text, font_size, background_color (rgba), color, size, size_hint, pos
  • bind(on_press=callback) ผูกเหตุการณ์กดปุ่ม
  • App().run() เริ่มลูปหลักของแอป