In this wxPython article we want to learn about How to Create wxPython List Box, so wxPython is powerful library for creating graphical user interfaces (GUIs) in Python. in this tutorial we want to talk about the process of creating a wxPython list box step by step.
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import wx app = wx.App() frame = wx.Frame(None, title='GeeksCoders - List Box Example') listbox = wx.ListBox(frame, choices=['Item 1', 'Item 2', 'Item 3', 'GeeksCoders']) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(listbox, 1, wx.EXPAND) frame.SetSizer(sizer) frame.Show() app.MainLoop() |
In the above code first we have imported our wxPython module.
1 |
import wx |
After that we need to create an instance of the wx.App class. this object will be the foundation of our GUI.
1 |
app = wx.App() |
Now we need to create a window to hold our list box. we can do this by creating an instance of the wx.Frame class, first argument (None) indicates that this frame has no parent, and the title argument sets the title of the frame.
1 |
frame = wx.Frame(None, title='GeeksCoders - List Box Example') |
To create a list box we need to create an instance of the wx.ListBox class, first argument (frame) tells the list box which window it belongs to. choices argument is a list of the items that will be displayed in the list box.
1 |
listbox = wx.ListBox(frame, choices=['Item 1', 'Item 2', 'Item 3', 'GeeksCoders']) |
Now that we have created the list box, we need to add it to the frame. We can do this using the Sizer class, wx.BoxSizer class is used to create a layout manager for the frame. in this case we creates a vertical sizer (wx.VERTICAL) that will contain the list box. after that we use the Add method to add the list box to the sizer.
1 2 3 |
sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(listbox, 1, wx.EXPAND) frame.SetSizer(sizer) |
Now that we have created our list box and added it to the frame, we can show the frame to the user.
1 |
frame.Show() |
And lastly we need to start the event loop that will handle user input and keep our GUI running.
1 |
app.MainLoop() |
Run the complete code and this will be the result
