Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python - Làm việc với nút bấm (Button) trong Kivy


Kivy là công cụ GUI đa nền tảng (Android, iOS, Linux, Windows). Viết một lần, chạy mọi nơi. Dùng chủ yếu cho ứng dụng Android nhưng cũng chạy được trên Desktop.

Button là Label có gán hành động khi nhấn (hoặc thả sau click/chạm). Có thể gán hàm callback và tùy chỉnh giao diện.

Ví dụ cơ bản

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))
        # Gán hàm callback khi nhấn
        btn.bind(on_press=self.callback)
        return btn

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

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

Giải thích

  • size_hint: tỷ lệ kích thước tương đối so với cha (0-1).
  • pos: vị trí tuyệt đối (x, y).
  • bind(on_press=...): gán sự kiện nhấn nút.
  • background_color và color: tuple RGBA (0-1).