In this wxPython article we want to learn about How to Create wxPython CheckBox with wx.CheckBox, wxPython is popular Python library that allows you to create desktop applications with graphical user interfaces. and CheckBox is one of the common GUI elements that you need to know about that.
For creating checkbox in wxPython, you need to import wxPython library. you can do it like this.
1 |
import wx |
After that you have imported wxPython library, you can create checkbox using wx.CheckBox class.
1 |
checkbox = wx.CheckBox(None, label='Enable Feature') |
By default checkbox will be unchecked. you can change the state of the checkbox by using SetValue() method. if you want to check the checkbox, you can set the value to True. if you want to uncheck the checkbox, you can set the value to False.
1 |
checkbox.SetValue(True) |
You can also check state of the checkbox by using GetValue() method. GetValue() method returns a boolean value. if the checkbox is checked, this method will return True. if the checkbox is unchecked this method will return False.
1 |
checkbox_state = checkbox.GetValue() |
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import wx class MyFrame(wx.Frame): def __init__(self): super().__init__(parent=None, title='Geekscoders.com - Checkbox Example') # Create box sizer to hold the checkbox box_sizer = wx.BoxSizer(wx.HORIZONTAL) # Create checkbox checkbox = wx.CheckBox(self, label='Enable Feature') # Add checkbox to the box sizer box_sizer.Add(checkbox, 0, wx.ALL, 5) # Set sizer for the frame self.SetSizer(box_sizer) if __name__ == '__main__': app = wx.App() frame = MyFrame() frame.Show() app.MainLoop() |
In the above example we have created a new class called MyFrame that extends from wx.Frame class. we have created box sizer to hold the checkbox, also we have created wxpython checkbox using wx.CheckBox class, and added the checkbox to the box sizer using Add() method. and finally we have set the sizer for the frame using the SetSizer() method.
Run the complete code this will be the result