Random Color Button Dialog in wxPython

  • Share this:

Code introduction


This function creates a dialog containing a button whose color changes when clicked.


Technology Stack : wxPython

Code Type : GUI Application

Code Difficulty : Intermediate


                
                    
import wx
import random

def random_color_button_dialog(parent, title):
    """
    This function creates a dialog with a random color button.
    The button changes its color when clicked.
    """
    # Create a dialog with a sizer
    dialog = wx.Dialog(parent, title=title, size=(200, 100))
    sizer = wx.BoxSizer(wx.VERTICAL)
    dialog.SetSizer(sizer)

    # Create a panel to hold the button
    panel = wx.Panel(dialog)
    sizer.Add(panel, 1, wx.EXPAND)

    # Create a button with a random color
    button = wx.Button(panel, label="Click Me")
    button.SetBackgroundColour(random.choice(['Red', 'Green', 'Blue', 'Yellow', 'Cyan', 'Magenta', 'Black', 'White']))
    panel.Bind(wx.EVT_BUTTON, lambda event: change_button_color(button))

    # Show the dialog
    dialog.ShowModal()
    dialog.Destroy()

def change_button_color(button):
    """
    This function changes the color of the button to a random color.
    """
    new_color = random.choice(['Red', 'Green', 'Blue', 'Yellow', 'Cyan', 'Magenta', 'Black', 'White'])
    button.SetBackgroundColour(new_color)

# JSON output
json_output = {
    "type": "GUI Application",
    "hard": "中级",
    "explain": "创建一个对话框,其中包含一个按钮,按钮的颜色在点击时改变。",
    "tench": "wxPython",
    "explain_en": "This function creates a dialog containing a button whose color changes when clicked.",
    "tench_en": "wxPython"
}                
              
Tags: