Randomly Generated Button GUI with wxPython

  • Share this:

Code introduction


This code creates a wxPython GUI application that randomly generates buttons on a panel and binds a click event handler to each button.


Technology Stack : wxPython, GUI application, button generation, event binding

Code Type : The type of code

Code Difficulty :


                
                    
import wx

def random_button_clicker(panel, event):
    # Create a random button with a random label
    button = wx.Button(panel, label=f"Button {wx.NewId()}")
    button.Bind(wx.EVT_BUTTON, random_button_clicker)

    # Add the button to the panel
    panel.Sizer.Add(button, 0, wx.ALL | wx.EXPAND, 5)

# Main application class
class MyApp(wx.App):
    def OnInit(self):
        # Create the main window
        self.frame = wx.Frame(None, title="Random Button Clicker", size=(300, 200))
        
        # Create a panel with a sizer
        panel = wx.Panel(self.frame)
        sizer = wx.BoxSizer(wx.VERTICAL)
        panel.SetSizer(sizer)
        
        # Add the random button clicker to the panel
        random_button_clicker(panel, None)
        
        # Show the main window
        self.frame.Show()
        
        return True

# Run the application
if __name__ == "__main__":
    app = MyApp(False)
    app.MainLoop()