Random Action Button in wxPython

  • Share this:

Code introduction


This code creates a simple wxPython application with a frame and a button. When the button is clicked, it randomly performs one of two actions: displaying a message box or changing the button label.


Technology Stack : wxPython

Code Type : wxPython GUI Application

Code Difficulty : Intermediate


                
                    
import wx
import random

def random_button_click(arg1, arg2):
    # Create a simple wxPython application with a frame and a button
    app = wx.App(False)
    frame = wx.Frame(None, title="Random Button Click", size=(300, 200))
    panel = wx.Panel(frame)
    button = wx.Button(panel, label="Click Me!", pos=(100, 75))
    
    # Bind the button click event to a handler function
    def on_button_click(event):
        # Randomly select between two actions: print a message or change the button label
        if random.choice([True, False]):
            wx.MessageBox(f"Argument 1: {arg1}, Argument 2: {arg2}", "Message", wx.OK | wx.ICON_INFORMATION)
        else:
            button.SetLabel("Clicked!")
    
    button.Bind(wx.EVT_BUTTON, on_button_click)
    frame.Show()
    app.MainLoop()                
              
Tags: