[파이썬] wxPython `wx.CheckBox`: 체크 박스

In this blog post, we will explore how to use the wx.CheckBox class in wxPython to create checkboxes in Python.

Introduction

Checkboxes are a common element in graphical user interfaces (GUIs) that allow users to select or deselect an option. They are useful for presenting a list of options where users can choose multiple items.

Getting Started

To use the wx.CheckBox class in wxPython, you first need to install wxPython library if you haven’t done so already. You can install it using pip:

pip install -U wxPython

Once you have wxPython installed, you can import the necessary modules:

import wx

Creating a Checkbox

To create a checkbox using wx.CheckBox, you need to create an instance of the class and specify its parent window. Here’s an example:

class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="Checkbox Example")

        panel = wx.Panel(self)
        checkbox = wx.CheckBox(panel, label="Check me")

        self.Show()


if __name__ == "__main__":
    app = wx.App()
    frame = MyFrame()
    app.MainLoop()

In this example, we create a MyFrame class that inherits from wx.Frame. Inside the __init__ method, we create a panel as a child of the frame and then create a wx.CheckBox widget with the label “Check me”. Finally, we show the frame using the Show() method.

Handling Checkbox Events

To handle events generated by the checkbox, you can bind a method to the checkbox’s EVT_CHECKBOX event. This method will be called whenever the checkbox’s state changes. Here’s an example:

class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="Checkbox Example")

        panel = wx.Panel(self)
        checkbox = wx.CheckBox(panel, label="Check me")
        checkbox.Bind(wx.EVT_CHECKBOX, self.on_checkbox_change)

        self.Show()

    def on_checkbox_change(self, event):
        checkbox = event.GetEventObject()
        if checkbox.GetValue():
            print("Checkbox is checked")
        else:
            print("Checkbox is unchecked")

In this example, we define the on_checkbox_change method that takes an event object as a parameter. We use the GetEventObject() method to get a reference to the checkbox that generated the event. We then check the checkbox’s value using the GetValue() method and print the appropriate message.

Conclusion

In this blog post, we learned how to create checkboxes using the wx.CheckBox class in wxPython. We also explored how to handle checkbox events. Checkboxes are a versatile form element that can be used to provide options for user selection in your Python GUI applications.