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

Python - Xử lý sự kiện Button trong Kivy


Kivy là thư viện Python mã nguồn mở cho phát triển ứng dụng giao diện đổi mới (multi-touch). Bài viết hướng dẫn xử lý sự kiện khi nhấn nút (Button).

Ví dụ tạo Button và Label trong BoxLayout ngang. Gán text ban đầu. Tạo sự kiện click thay đổi text cả Button và Label. Chỉ cần một file Python.

Ví dụ

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

class ButtonPressApp(App):
    def __init__(self):
        super(ButtonPressApp, self).__init__()
        self.btn = Button(text='Submit Button')
        self.lbl = Label(text='Some text here.')

    def build(self):
        self.btn.bind(on_press=self.click_event)
        layout = BoxLayout()
        layout.orientation = 'horizontal'
        layout.add_widget(self.btn)
        layout.add_widget(self.lbl)
        return layout

    def click_event(self, obj):
        self.btn.background_normal = ''
        self.btn.color = (1, 0, 0, 0.8)
        self.btn.text = 'Button Pressed'
        self.lbl.text = 'Text Changed'

MainLayout = ButtonPressApp()
MainLayout.run()

Kết quả:

Đầu ra

Trước khi nhấn nút.

Python - Xử lý sự kiện Button trong Kivy

Sau khi nhấn nút.

Python - Xử lý sự kiện Button trong Kivy