0

There are variety of cursors available using the wx.StockCursor() in wxPython:

# a look at cursors and wx.StockCursor()

import wx

class MyFrame(wx.Frame):
    """create a color frame, inherits from wx.Frame"""
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, wx.ID_ANY, "Left click the mouse",
            size=(500, 300))
        self.SetBackgroundColour('yellow')
        self.count = 0
        # just to show you how to set it, actually the default cursor
        self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
        # bind mouse left click event
        self.Bind(wx.EVT_LEFT_DOWN, self.onLeftDown)

    def onLeftDown(self, event):
        """left mouse button is pressed"""
        # get (x, y) position tuple
        pt = event.GetPosition()
        # put cursor globals in as strings so the name can be shown
        cursors = ['wx.CURSOR_SPRAYCAN', 'wx.CURSOR_NO_ENTRY', 'wx.CURSOR_BULLSEYE', 
            'wx.CURSOR_CROSS', 'wx.CURSOR_HAND', 'wx.CURSOR_IBEAM', 
            'wx.CURSOR_MAGNIFIER', 'wx.CURSOR_PENCIL', 'wx.CURSOR_RIGHT_ARROW', 
            'wx.CURSOR_QUESTION_ARROW', 'wx.CURSOR_WAIT', 'wx.CURSOR_ARROWWAIT',
            'wx.CURSOR_PAINT_BRUSH', 'wx.CURSOR_SIZING']
        s = "cursor = %s   at point %s" % (cursors[self.count], str(pt))
        self.SetTitle(s)
        # use eval() to get the integer value back
        int_val = eval(cursors[self.count])
        self.SetCursor(wx.StockCursor(int_val))
        self.count += 1
        if self.count >= len(cursors):
            self.count = 0


app = wx.App(0)
MyFrame(None).Show()
app.MainLoop()
0

An example on how to load an image onto a wxPython canvas sized to the image. Also, point the mouse to any part of the image, click and display the color pixel pointed to:

# show an image from a file using a wx.ClientDC() canvas
# any previous image on the canvas can be cleared
# wx.ClientDC() does not use the wx.PaintEvent
# optionally show rgb colour tuple at point (x, y) clicked

import wx

class ImagePanel(wx.Panel):
    """ create a panel with a canvas to draw on"""
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, wx.ID_ANY)
        self.parent = parent
        # pick an image file you have in your working folder
        # (can be a .jpg, .png, .gif, or .bmp image file)
        image_file = 'Zingerman1.jpg'
        self.bmp = wx.Bitmap(image_file)
        image_width = self.bmp.GetWidth()
        image_height = self.bmp.GetHeight()

        # set frame size (also panel) to image size
        parent.SetClientSize((image_width, image_height))

        # set special cursor
        self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))

        # this small delay is needed to allow image loading first
        wx.FutureCall(50, self.make_canvas)

        # bind mouse left click event
        self.Bind(wx.EVT_LEFT_DOWN, self.onClick)

        # optionally show some image information
        info = "%s  %dx%d  (click mouse)" %\
            (image_file, image_width, image_height)
        # the parent is the frame
        self.parent.SetTitle(info)

    def make_canvas(self):
        self.dc = wx.ClientDC(self)
        # clear the canvas
        self.dc.Clear()
        # draw the image
        self.dc.DrawBitmap(self.bmp, 0, 0, True)

    def onClick(self, event):
        # get (x, y) position tuple
        pt = event.GetPosition()
        colour = self.dc.GetPixelPoint(pt)
        s = "RGB = %s at point %s" % (str(colour[:3]), str(pt))
        self.parent.SetTitle(s)


app = wx.App() 
# create window/frame
frame = wx.Frame(None, wx.ID_ANY, size=(400, 300))
# create the panel instance
ImagePanel(frame)
# show the frame
frame.Show(True)
app.MainLoop()
Attachments Zingerman1.jpg 35.74 KB
0

Amazing how a bunch of lines can create a nifty pattern, here is an example using a wxPython canvas and a simple DrawLinePoint() function:

# draw a line pattern using a wx.ClientDC() canvas
# wx.ClientDC() does not use the wx.PaintEvent

import wx
import math

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(600, 400))
        self.SetBackgroundColour('white')
        # this small millisecond delay is needed
        wx.FutureCall(10, self.draw_lines)

    def draw_lines(self):
        # create the canvas to draw on
        dc = wx.ClientDC(self)

        # set line colour and thickness (pixels)
        dc.SetPen(wx.Pen("red", 1))

        # get the width and height of the canvas (the client)
        width, height = self.GetClientSizeTuple()

        # set the dc origin to the canvas center
        dc.SetDeviceOrigin(width//2, height//2)

        # note that this point is actually the center of the canvas
        point1 = (0, 0)

        # calculate the usable radius
        radius = math.hypot(width//2, height//2)

        # not that the angle is in radians
        angle = 0
        notch = 4 * math.pi/360
        while (angle < 2 * math.pi):
            # calculate x and y for each end point
            x = radius * math.cos(angle)
            y = radius * math.sin(angle)
            point2 = (x, y)
            dc.DrawLinePoint(point1, point2)
            # advance the angle a notch
            angle += notch


app = wx.App()
MyFrame(None, 'draw a line pattern with DrawLinePoint()').Show(True)
app.MainLoop()
0

This is one way to create a wxPython canvas with a background pattern on it:

# the wx.PaintDC() surface is wxPython's canvas
# create a background pattern on the canvas

import wx

class ImagePanel(wx.Panel):
    """draw lines on a panel's wx.PaintDC surface"""
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, wx.ID_ANY)

        wx.EVT_PAINT(self, self.on_paint)

    def on_paint(self, event=None):
        dc = wx.PaintDC(event.GetEventObject())
        # set the background colour
        dc.SetBackground(wx.Brush("WHITE"))
        dc.Clear()
        # give it a pattern using a brushed full sized rectangle
        dc.SetBrush(wx.Brush("LIGHT GREY", wx.CROSSDIAG_HATCH))
        windowsize= self.GetSizeTuple()
        dc.DrawRectangle(0, 0, windowsize[0], windowsize[1])

        # draw something cute
        for x in range(10, 180, 10):
            y = x
            r = x
            dc.SetPen(wx.Pen('red', 3))
            dc.DrawCircle(x, y, r)
            dc.SetPen(wx.Pen('blue', 3))
            dc.DrawSpline(((10, 200), (x, y), (2*x, 400-y), (370, 200)))


app = wx.App()
title = "A wx drawing surface with a background"
frame = wx.Frame(None, wx.ID_ANY, title, size=(380, 400))
ImagePanel(frame)
frame.Show(True)
app.MainLoop()
0

Taking a look at wxPython's w.Image() widget, and how you can and could adjust the images red, green, blue and alpha content:

# experimants with wxPython wxImage(name, type)
# adjust the alpha (transparency) of an image
"""
type:
wx.BITMAP_TYPE_BMP  Load a Windows bitmap file
wx.BITMAP_TYPE_GIF  Load a GIF bitmap file
wx.BITMAP_TYPE_JPEG  Load a JPEG bitmap file
wx.BITMAP_TYPE_PNG  Load a PNG bitmap file
wx.BITMAP_TYPE_PCX  Load a PCX bitmap file
wx.BITMAP_TYPE_PNM  Load a PNM bitmap file
wx.BITMAP_TYPE_TIF  Load a TIFF bitmap file
wx.BITMAP_TYPE_XPM  Load a XPM bitmap file
wx.BITMAP_TYPE_ICO  Load a Windows icon file (ICO)
wx.BITMAP_TYPE_CUR  Load a Windows cursor file (CUR)
wx.BITMAP_TYPE_ANI  Load a Windows animated cursor file (ANI)
wx.BITMAP_TYPE_ANY  Will try to autodetect the format
"""

import wx

class ImagePanel(wx.Panel):
    """draw lines on a panel's wx.PaintDC surface"""
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, wx.ID_ANY)
        # pick an image file you have in the working folder
        # (can be a .jpg, .png, .gif, .bmp image file)
        image_file = 'Pythonhand3.jpg'
        self.image= wx.Image(image_file, wx.BITMAP_TYPE_JPEG)
        image_width = self.image.GetWidth()
        image_height = self.image.GetHeight()
        # set frame size (also panel) to image size
        parent.SetClientSize((image_width+20, image_height+20))
        # call on_paint() to create the canvas
        wx.EVT_PAINT(self, self.on_paint)

    def on_paint(self, event):
        dc = wx.PaintDC(self)
        # reduces flicker
        #dc = wx.BufferedDC(dc)
        # set the background colour
        dc.SetBackground(wx.Brush("WHITE"))
        dc.Clear()
        # give it a pattern
        dc.SetBrush(wx.Brush("GREY", wx.CROSSDIAG_HATCH))
        windowsize= self.GetSizeTuple()
        dc.DrawRectangle(0, 0, windowsize[0], windowsize[1])

        # adjust r g b and alpha of image
        # AdjustChannels(fr, fg, fb, fa)
        # adjust the the red, green blue and alpha factors
        # from 0.0 to 2.0 to see the effects
        image = self.image.AdjustChannels(1.0, 1.0, 1.0, 0.6)
        bmp = wx.BitmapFromImage(image)
        dc.DrawBitmap(bmp, 10, 10, True)


app = wx.App()
title = "wx.Image() transparent"
frame = wx.Frame(None, wx.ID_ANY, title)
ImagePanel(frame)
frame.Show(True)
app.MainLoop()
Attachments PythonHand3.jpg 21.13 KB
0

Another example of plotting with wxPython's wx.lib.plot module. Draws two line graphs of trig functions and saves the graph to an image file ...

# using wxPython's wx.lib.plot.PlotCanvas()
# to show a line graph of some trig functions
# also save graph to an image file

import wx
import wx.lib.plot
import math

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)

        # calculate data lists of (x, y) tuples
        # x is in radians
        sin_data = []
        cos_data = []
        x = 0
        while True:
            y = math.sin(x*x)
            sin_data.append((x, y))
            y = math.sin(x*x) + math.cos(x**0.5)
            cos_data.append((x, y))
            x += 0.01
            if x > 4*math.pi:
                break

        # set up the plotting canvas
        plot_canvas = wx.lib.plot.PlotCanvas(self)
        # get client usable size of frame
        frame_size = self.GetClientSize()
        # needed for SaveFile() later
        plot_canvas.SetInitialSize(size=frame_size)
        # optional allow scrolling
        plot_canvas.SetShowScrollbars(True)
        # optional drag/draw rubberband area to zoom
        # doubleclick to return to original
        # right click to shrink
        plot_canvas.SetEnableZoom(True)
        # optional
        # set the tick and axis label font size (default is 10 point)
        plot_canvas.SetFontSizeAxis(point=8)
        # set title font size (default is 15 point)
        plot_canvas.SetFontSizeTitle(point=10)

        # connect (x, y) points in data list with a line
        sin_lines = wx.lib.plot.PolyLine(sin_data, colour='red', width=1)
        cos_lines = wx.lib.plot.PolyLine(cos_data, colour='blue', width=1)

        # assign lines, title and axis labels
        gc = wx.lib.plot.PlotGraphics([sin_lines, cos_lines],
            'red=sin(x*x)   blue=sin(x*x) + cos(x**0.5)',
            'X Axis (radians)', 'Y Axis')
        # draw the plot and set x and y axis sizes
        plot_canvas.Draw(gc, xAxis=(0, 7), yAxis=(-2, 2))

        # optional save graph to an image file
        plot_canvas.SaveFile(fileName='trig1.jpg')


app = wx.App(0)
# create a MyFrame instance and show the frame
caption = "wx.lib.plot.PlotCanvas() Line Graph"
MyFrame(None, caption, (400, 300)).Show()
app.MainLoop()
0

Use wxPython's wx.lib.dialogs.ScrolledMessageDialog() if you have to bring up a message box with a large amount of information:

# for a large information/message text uase wxPython's
# wx.lib.dialogs.ScrolledMessageDialog() widget

import wx
import wx.lib.dialogs

class MyPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, wx.ID_ANY)
        self.SetBackgroundColour("blue")

        # create an input widget
        self.button1 = wx.Button(self, wx.ID_ANY,
            label='The Zen of Python', pos=(10, 20))
        # bind mouse event to an action
        self.button1.Bind(wx.EVT_BUTTON, self.onAction)

    def onAction(self, event):
        """ some action code"""
        # pick an informative textfile you have in the
        # working directory (or use full path)
        fin = open("ZenPy.txt", "r")
        info = fin.read()
        fin.close()

        dlg = wx.lib.dialogs.ScrolledMessageDialog(self, info,
            "The Zen of Python, by Tim Peters ...")
        dlg.SetBackgroundColour('brown')
        dlg.ShowModal()


info_text = """\
The Zen of Python, by Tim Peters ...

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one, and preferably only one obvious way to do it.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea, let's do more of them!
"""

# create a file for testing
fout = open("ZenPy.txt", "w")
fout.write(info_text)
fout.close()

app = wx.App(0)
# create a frame, no parent, default ID, title, size
caption = "wx.lib.dialogs.ScrolledMessageDialog()"
frame = wx.Frame(None, wx.ID_ANY, caption, size=(400, 310))
MyPanel(frame)
frame.Show(True)
app.MainLoop()
0

wxPython supplies a progressbar called wx.Gauge(). Here is a short test code:

# a templet with wx.Frame, wx.Panel, wx.Slider and wx.Gauge
# wx.Gauge(parent, id, range, pos, size, style)
# (on Windows XP the slider responds to the mouse-wheel)
# sorry, but the gauge markers come only in green ar this time
# wx.Slider(parent, id, value, minValue, maxValue, pos, size, style)

import wx
import time

class MyPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, wx.ID_ANY)
        self.SetBackgroundColour("white")

        # initial value = 50, minvalue = 0, maxvalue = 100
        self.slider = wx.Slider(self, wx.ID_ANY, value=50, minValue=0,
            maxValue=100, pos=(10, 10), size=(390, 50),
            style=wx.SL_HORIZONTAL|wx.SL_AUTOTICKS|wx.SL_LABELS)

        # range set to 0 to 100, default style is wx.GA_HORIZONTAL
        # other style option is wx.GA_VERTICAL
        self.gauge1 = wx.Gauge(self, wx.ID_ANY, range=100, pos=(10, 70),
            size=(390, 25), style=wx.GA_HORIZONTAL)
        self.gauge2 = wx.Gauge(self, wx.ID_ANY, range=100, pos=(375, 100),
            size=(25, 155), style=wx.GA_VERTICAL)

        # set gauges to initial slider position
        self.pos1 = self.slider.GetValue()
        self.gauge1.SetValue(self.pos1)
        self.gauge2.SetValue(self.pos1)

        s1 = "the gauge is bound to the slider,"
        s2 = "just click and drag the pointer"
        self.label1 = wx.StaticText(self, wx.ID_ANY, s1+s2, pos=(10, 100))
        self.label2 = wx.StaticText(self, wx.ID_ANY,
            "the gauge can use a timer loop" , pos=(10, 140))
        self.button = wx.Button(self, wx.ID_ANY, "Press to start timer",
            pos=(10, 170))

        # respond to changes in slider position ...
        self.slider.Bind(wx.EVT_SLIDER, self.sliderUpdate)
        # respond to the click of the button
        self.button.Bind(wx.EVT_BUTTON, self.button1Click)

    def sliderUpdate(self, event):
        # get the slider position
        self.pos1 = self.slider.GetValue()
        # set the gauge positions
        self.gauge1.SetValue(self.pos1)
        self.gauge2.SetValue(self.pos1)

    def button1Click(self, event):
        for k in range(101):
            # move the progress bar/gauge
            self.gauge1.SetValue(k)
            self.gauge2.SetValue(k)
            # move the slider too for the fun of it
            self.slider.SetValue(k)
            # 0.015 second intervals
            time.sleep(0.015)
        #print event.GetEventType()  # test


app = wx.App(0)
frame = wx.Frame(None, wx.ID_ANY, "wx.Gauge Test", size=(420, 300))
MyPanel(frame)
frame.Show(True)
app.MainLoop()
0

You can use the wxPython wx.ColourDialog to select a colour you like ...

# test wxPython's
# wx.ColourDialog() to select a colour

import wx

class MyPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, wx.ID_ANY)
        self.SetBackgroundColour("yellow")

        self.button = wx.Button(self, wx.ID_ANY,
            label='Pick a Colour', pos=(10, 10))
        # bind mouse event to an action
        self.button.Bind(wx.EVT_BUTTON, self.pickColour)
        # create an ouput widget
        self.label = wx.StaticText(self, wx.ID_ANY, "", (10, 80))
        self.label.SetBackgroundColour("white")

    def pickColour(self, event):
        """bring up the ColourDialog"""
        dlg = wx.ColourDialog(self)
        # get full colour dialog, default is abbreviated version
        dlg.GetColourData().SetChooseFull(True)
        if dlg.ShowModal() == wx.ID_OK:
            data = dlg.GetColourData()
            # tuple (r, g, b, a)
            rgba = data.GetColour()
            # tuple (r, g, b)
            rgb = data.GetColour().Get()
            s = 'You selected colour (r, g, b) = %s' % str(rgb)
            self.label.SetLabel(s)
            self.SetBackgroundColour(rgb)
            # clear old color, set to new color
            self.ClearBackground()
        dlg.Destroy()


app = wx.App()
# create a frame, no parent, default ID, title, size
caption = "Test wx.ColourDialog()"
frame = wx.Frame(None, wx.ID_ANY, caption, size=(400, 310))
MyPanel(frame)
frame.Show(True)
app.MainLoop()
0

How do I use wx.Gauge to show the progress of very slow process?

# show the progress of slow process with wx.Gauge widget

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
        panel = wx.Panel(self)

        # for instance process takes total seconds
        total = 50
        # range set to 0 to total
        self.gauge1 = wx.Gauge(panel, wx.ID_ANY, range=total, 
            pos=(10, 10), size=(390, 15), style=wx.GA_HORIZONTAL)

        self.val = 1

        self.timer = wx.Timer(self)
        interval = 1000  # (in milliseconds)
        self.timer.Start(interval)
        # bind EVT_TIMER event and
        # update the gauge every interval
        self.Bind(wx.EVT_TIMER, self.update_gauge)

        # code your process here ...

    def update_gauge(self, event):
        """move the gauge one notch"""
        self.gauge1.SetValue(self.val)
        self.val += 1


app = wx.App(0)
# create one MyFrame instance and then show the frame
MyFrame(None, 'use wx.Gauge to show progress', (420, 300)).Show()
app.MainLoop()
0

I was in search for wx_IDs and one guy presented me with some code with for loop!
I modified a little bit and here is a code for simple preogram that will show all available built in wx.IDs

import wx

class Frame1(wx.Frame):
    def __init__ (self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(400, 400))
	self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE)
        
	x = dir(wx)

	for y in x:
	    if y.find('ID_')!=-1:
		search = y + "\n"
		self.text.write(search)
		

app = wx.App(False)
f = Frame1(None, -1, "wx.IDs")
f.Centre()
f.Show(True)
app.MainLoop()

Editor's note:
Careful when copying this code to your editor, it uses mixed spaces and tabs.

0

If you ever need the values of wx ID's as well as any other constants in wxPython here is a way to do it:

import wx

class MainFrame(wx.Frame):
    def __init__ (self):
        wx.Frame.__init__(self,None,title = "ID's and Values", size=(400, 400))
        self.text = wx.TextCtrl(self, wx.ID_ANY, style = wx.TE_MULTILINE)
        
       
        for f in wx.__dict__:
            if f.startswith("ID_"):
                t = f+'  -->  '+str(wx.__dict__[f])+'\n'
                self.text.write(t)
        self.Show()
        

app = wx.App(False)
f = MainFrame()
app.MainLoop()

If you want a full dictionary of values try this:

import wx

class MainFrame(wx.Frame):
    def __init__ (self):
        wx.Frame.__init__(self,None,title = "ID's and Values", size=(400, 400))
        self.text = wx.TextCtrl(self, wx.ID_ANY, style = wx.TE_MULTILINE)
       
        for f in wx.__dict__:
            try:
                t =  f+'  -->  '+str(int(wx.__dict__[f]))+'\n'
                self.text.write(t)
            except:
                pass
        
        self.Show()
        

app = wx.App(False)
f = MainFrame()
app.MainLoop()

Notive that bit where is goes str(int(wx.__dict__[f])) ? Thats to make sure that anything that has a value that isnt an int will not work as there will be an error and the program will skip it.

1

The wx.RichTextCtrl() widget allows the user to create formatted text with color, size, font, bullets, images and more:

# experiment with wxPython's
# wx.RichTextCtrl(parent, id, value, pos, size, style=wx.RE_MULTILINE, 
#    validator, name)
# allows you to create formatted text with color, size, font, images ...
# snee

import wx
import wx.richtext

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
        self.SetBackgroundColour("white")
        
        self.rich = wx.richtext.RichTextCtrl(self, wx.ID_ANY, value="")
        self.rich.WriteText("Default is black text.\n")
        self.rich.BeginBold()
        self.rich.WriteText("Write this text in bold")
        self.rich.BeginTextColour('red')
        self.rich.WriteText(" and this text in bold and red.\n")
        self.rich.EndTextColour()
        self.rich.EndBold()
        
        self.rich.BeginFontSize(30)
        self.rich.WriteText("This text has point size 30\n")
        self.rich.EndFontSize()
        
        font = wx.Font(16, wx.SCRIPT, wx.NORMAL, wx.LIGHT)
        self.rich.BeginFont(font)
        self.rich.WriteText("This text has a different font\n")
        self.rich.EndFont()
        self.rich.Newline()
        # indent the next items 100 units (tenths of a millimeter)
        self.rich.BeginLeftIndent(100) 
        
        # insert an image you have in the work directory
        # or give the full path, can be .bmp .gif .png .jpg
        image_file = "Duck2.jpg"
        image= wx.Image(image_file, wx.BITMAP_TYPE_ANY)
        # wx.BITMAP_TYPE_ANY   tries to autodetect the format
        self.rich.WriteImage(image)
        self.rich.Newline()
        self.rich.EndLeftIndent()
        

app = wx.App()
mytitle = 'testing wx.RichTextCtrl'
width = 560
height = 400
# create the MyFrame instance and show the frame
MyFrame(None, mytitle, (width, height)).Show()
app.MainLoop()
Attachments Duck2.jpg 11.26 KB
0

An example on how to pick the rgb colour value on a wx.PaintDC canvas with GetPixel(x, y) ...

# draw a colourful rectangle on a wx.PaintDC surface
# and get the colour at the point of a mouse click
# using wx.PaintDC's GetPixel(x, y)
# tested with Python25 and wxPython28  by vegaseat

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
        # this will also be the canvas surface color
        self.SetBackgroundColour('white')
        # bind the frame to the paint event
        wx.EVT_PAINT(self, self.onPaint)
        # bind the left mouse button click event
        self.Bind(wx.EVT_LEFT_DOWN, self.onLeftDown)

    def onPaint(self, event=None):
        # this is the wxPython drawing surface/canvas
        self.dc = wx.PaintDC(self)
        # create a concentric gradient fill area
        # rect has upper left corner coordinates (x, y)
        x = 10
        y = 10
        width = 450
        height = 450
        center = ((width-x)/2, (height-y)/2)
        self.dc.GradientFillConcentric((x, y, width, height),
            'red', 'blue', center)

    def onLeftDown(self, event):
        """left mouse button is pressed"""
        # get the (x, y) position tuple
        x, y = event.GetPosition()
        # get (r,g,b) colour of pixel at point (x,y)
        r, g, b = self.dc.GetPixel(x, y)[:3]
        # show result in frame's titlebar
        s = "Colour at (x=%s,y=%s) is (r=%s,g=%s,b=%s)" % (x, y, r, g, b)
        self.SetTitle(s)


app = wx.App()
mytitle = "click on a point to show colour"
width = 480
height = 510
MyFrame(None, mytitle, (width, height)).Show()
app.MainLoop()
0

When using a richTextCtrl on a Panel often comes up with problems such as when you press Enter\Return to make a new line nothing happens. Here is an example to show people who have no idea what problem i am taking about. Try using this code and then making a new line. It will not work.

iimport wx
import wx.richtext as rc

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, size = (120,140))
        self.panel = wx.Panel(self)   #Notice you cant press enter and get a new line?
        
        self.rich = rc.RichTextCtrl(self.panel, size = (100,100))
        self.Show()
        
        
app = wx.App(0)
frame = MainFrame()
app.MainLoop()

But to fix it! Just add a style of 0 to the panel!

import wx
import wx.richtext as rc

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, size = (120,140))
        self.panel = wx.Panel(self, style = 0)   #Yay it works
        
        self.rich = rc.RichTextCtrl(self.panel, size = (100,100))
        self.Show()
        
        
app = wx.App(0)
frame = MainFrame()
app.MainLoop()

Hope that helps anyone that had that problem, i know it stumped me for hours!

0

One way to present highly formatted text like text with superscripts is to use wxPython's wx.html.HtmlWindow widget and simplified html code:

# exploring wxPython's
# wx.html.HtmlWindow(parent, id, pos, size, style, name)

import wx
import wx.html

class MyPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, wx.ID_ANY)
        self.SetBackgroundColour("yellow")
        
        htmlwin = wx.html.HtmlWindow(self, wx.ID_ANY, 
            pos=(10,30), size=(200,100))
        htmlwin.SetPage(html_code)


# use simple HTML code ...
html_code = """\
x<sup>3</sup> + y<sup>2</sup> - 15 = 0
"""

app = wx.App(0)
# create a frame, no parent, default ID, title, size
caption = "superscript text with wx.html.HtmlWindow"
frame = wx.Frame(None, wx.ID_ANY, caption, size=(400, 210))
MyPanel(frame)
frame.Show()
app.MainLoop()
Attachments htmlwindow3.jpg 10.81 KB
0

The wx.html.HtmlWindow widget is also very useful to show text in changing size and colour:

# using wxPython's
# wx.html.HtmlWindow(parent, id, pos, size, style, name)
# to show colourful text using relatively simple html code

import wx
import wx.html

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize, html_code1, html_code2):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle,
            size=mysize)

        # create an html label/window
        htmlwin1 = wx.html.HtmlWindow(self, wx.ID_ANY)
        htmlwin1.SetPage(html_code1)
        
        htmlwin2 = wx.html.HtmlWindow(self, wx.ID_ANY)
        htmlwin2.SetPage(html_code2)
        
        # position the labels with a box sizer
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        sizer_v.Add(htmlwin1, proportion=1, flag=wx.EXPAND)
        sizer_v.Add(htmlwin2, proportion=2, flag=wx.EXPAND)
        self.SetSizer(sizer_v)


# simple HTML code ...
# text between <B> and </B> is bold
# <BR> inserts a line break (or new line)
# text between <FONT color="blue"> and </FONT> is that color
# add size to the FONT tag
html_code1 = """\
This shows you how to display text in color
<BR>
<FONT color="blue">like blue text</FONT>
<FONT color="red"> or red text</FONT>
<B> or maybe just bold ...</B>
<BR><BR>
<FONT color="green" size=5>
You are in extreme
<FONT color="red" size=5>danger</FONT>
standing so close!
</FONT>
"""

# a few more HTML tags ...
# use <BODY> tags to add a background colour
# text between <H3> and </H3> is header size
# etc. etc. just experiment with the <> tags
html_code2 = """\
<BODY bgcolor="#FFE47E">
look at the new background colour ...
<H3>large header size</H3><H2>larger header size</H2>
<BR>
<FONT size="+4">even larger font size</FONT>
<BR><BR>
<FONT color="red" size="+4">larger </FONT>
<FONT color="green" size="+4">size </FONT>
<FONT color="blue" size="+4">and </FONT>
<FONT color="magenta" size="+4">color</FONT>
<BR>
</BODY>
"""

app = wx.App()
mytitle =  "wx.html.HtmlWindow for HTML formatted text"
width = 450
height = 350
frame = MyFrame(None, mytitle, (width, height), html_code1, html_code2)
frame.Show(True)
frame.Center()
app.MainLoop()
Attachments html_label.jpg 33.53 KB
0

If you want to delay a function call in wxPython it is best to use function wx.FutureCall(delaytime, function) ...

# use wx.FutureCall() to call a function after a set time
# allows present process to go on

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle):
        wx.Frame.__init__(self, parent, -1, mytitle, size=(450, 300))
        self.SetBackgroundColour('red')
        # call change_colour() after 2000 milliseconds (2 seconds)
        wx.FutureCall(2000, self.change_colour)

    def change_colour(self):
        self.SetBackgroundColour('green')
        self.ClearBackground()


app = wx.App(0)
MyFrame(None, 'change colour to green after 2 seconds').Show()
app.MainLoop()
0

This little program will browse for a sound file and then play it when you click the play button ...

# exploring wxPython's
# wx.Sound(fileName, isResource=False) and
# wx.lib.filebrowsebutton.FileBrowseButton(parent,labelText,fileMask)
# vega

import wx
import wx.lib.filebrowsebutton

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle):
        wx.Frame.__init__(self, parent, -1, mytitle, size=(600, 90))
        self.SetBackgroundColour("green")
        panel = wx.Panel(self)

        self.fbb = wx.lib.filebrowsebutton.FileBrowseButton(panel,
            labelText="Browse for a WAVE file:", fileMask="*.wav")
        play_button = wx.Button(panel, -1, " Play ")
        self.Bind(wx.EVT_BUTTON, self.onPlay, play_button)

        # setup the layout with sizers
        # line up widgets horizontally
        hsizer = wx.BoxSizer(wx.HORIZONTAL)
        hsizer.Add(self.fbb, 1, wx.ALIGN_CENTER_VERTICAL)
        hsizer.Add(play_button, 0, wx.ALIGN_CENTER_VERTICAL)
        
        # create a border space
        border = wx.BoxSizer(wx.VERTICAL)
        border.Add(hsizer, 0, flag=wx.ALL|wx.EXPAND, border=10)
        # only neeed to set this sizer since it contains the hsizer
        panel.SetSizer(border)

    def onPlay(self, event):
        """the play button has been clicked"""
        filename = self.fbb.GetValue()
        sound = wx.Sound(filename)
        sound.Play(wx.SOUND_ASYNC)


app = wx.App(0)
mytitle = "wx.lib.filebrowsebutton.FileBrowseButton and wx.Sound"
MyFrame(None, mytitle).Show()
app.MainLoop()
0

Let's get a little playful and display a text in rainbow colors:

# use wxPython's wx.richtext.RichTextCtrl
# to create rainbow colored text

import wx
import wx.richtext

class MyFrame(wx.Frame):
    def __init__(self, parent, title, rainbow_text):
        wx.Frame.__init__(self, parent, -1, title, size=(560, 220))
        self.SetBackgroundColour("white")
        
        self.rich = wx.richtext.RichTextCtrl(self, -1, value="")
        self.rich.BeginFontSize(40)
        for c, colour in rainbow_text:
            self.rich.BeginTextColour(colour)
            self.rich.WriteText(c)
            self.rich.EndTextColour()


rainbow = ['red', 'coral', 'yellow', 'green', 'blue']

text = """
 Welcome to fabulous
        Las Vegas"""

# create a list of (char, colour) tuples
rainbow_text = []
ix = 0
for c in text:
    if c.isalpha():
        colour = rainbow[ix]
        if ix < len(rainbow)-1:
            ix += 1
        else:
            ix = 0
    else:
        colour = 'white'
    rainbow_text.append((c, colour))

app = wx.App(0)
title = 'Rainbow Text'
MyFrame(None, title, rainbow_text).Show()
app.MainLoop()
Attachments wxrichtext1.jpg 20.58 KB
2

I think we may have talked about this before, but I can't find it. Here is a way to use a sound file inside the Python code and play it. First create a base64 encoded string of the binary sound file:

# create a base64 encoded string from binary sound data
# and limit the length of each data line to n characters
# ene

import base64

def text_lines(data, n):
    """
    write a long one line text as lines of n char each
    """
    s = ""
    for ix, c in enumerate(data):
        if ix % n == 0 and ix != 0:
            s += c + '\n'
        else:
            s += c
    return s

# pick a wave file that is in the working folder
wave_file = "pop.wav"
# this is a binary read
data = base64.b64encode(open(wave_file, 'rb').read())
data = text_lines(data, 70)
print "wav_base64='''\\\n" + data + "'''"

"""
highlight and copy the resulting base64 wav string to embed in program
code, use wav = base64.b64decode(wav_base64) to decode to binary data:

wav_base64='''\
UklGRuABAABXQVZFZm10IBAAAAABAAEAESsAABErAAABAAgAZGF0YbsBAACAgICAgICAgIC
AgICAfX12aVtQS0hJSk5TZpWyv8LBwMC/vry2nWxLPTs9PT5AR05pn77BwcC/vruxlGtJP
T09PkBHU3qrv8DAv7+7tKiGWUA8PT4+Qk1tm7fAv7++ubKmhl1CPD0+P0NPbZayv8C/vbe
vooNdRD0+PkBIWXWVrru/vbmypo5uU0I+P0NLWG6JorO7vLm0rJyBZlBEQkNIUF5xiJ2wu
bq4s6qZg21ZTUhITFRhcoaaqLGzsayilIFvYFVQUFNZY29/j52orKunnpKFdmheWFVWWmF
seYiXoqmrqaKXi390amRfXmBka3aDj5ifoqGemZGIfXJpY2FiZmx0fYePlpqcmpSNhHpyb
Wloam91foaNk5eXlZGMhH12b2xqam1xd32Ei5CVlpSPiYF6dHFvbnByd36Fi4+SkY6KhoN
+end3d3h8gYaKjIyMioeDf3t4dnZ3eX2BhYiKi4uJhoJ+eXZ1dnd6fICFiY2PjoyHgnx3d
XNzdHZ6f4WKjpCPjIiEf3t3dHNzdXh8goeLjY2NiYWBfHh0cnJzdnl9gYSGh4aFg398eXd
2d3l8foCChIaIh4aEgQA='''

"""

Now you can transfer the result to your Python program and play the sound without having to attach the sound file:

# playing a base64 encoded wave sound string with wxPython's
# wx.SoundFromData(sound_data) and sound.Play()
# ene

import wx
import base64

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize, sound_data):
        wx.Frame.__init__(self, parent, -1, mytitle, size=mysize)
        self.SetBackgroundColour("blue")
        # use a small delay to display the frame before sound starts
        wx.FutureCall(100, self.play_sound)

    def play_sound(self):
        sound = wx.SoundFromData(sound_data)
        # wx.SOUND_SYNC --> sound plays completely through
        for k in range(10):
            sound.Play(wx.SOUND_SYNC)


wav_base64='''\
UklGRuABAABXQVZFZm10IBAAAAABAAEAESsAABErAAABAAgAZGF0YbsBAACAgICAgICAgIC
AgICAfX12aVtQS0hJSk5TZpWyv8LBwMC/vry2nWxLPTs9PT5AR05pn77BwcC/vruxlGtJP
T09PkBHU3qrv8DAv7+7tKiGWUA8PT4+Qk1tm7fAv7++ubKmhl1CPD0+P0NPbZayv8C/vbe
vooNdRD0+PkBIWXWVrru/vbmypo5uU0I+P0NLWG6JorO7vLm0rJyBZlBEQkNIUF5xiJ2wu
bq4s6qZg21ZTUhITFRhcoaaqLGzsayilIFvYFVQUFNZY29/j52orKunnpKFdmheWFVWWmF
seYiXoqmrqaKXi390amRfXmBka3aDj5ifoqGemZGIfXJpY2FiZmx0fYePlpqcmpSNhHpyb
Wloam91foaNk5eXlZGMhH12b2xqam1xd32Ei5CVlpSPiYF6dHFvbnByd36Fi4+SkY6KhoN
+end3d3h8gYaKjIyMioeDf3t4dnZ3eX2BhYiKi4uJhoJ+eXZ1dnd6fICFiY2PjoyHgnx3d
XNzdHZ6f4WKjpCPjIiEf3t3dHNzdXh8goeLjY2NiYWBfHh0cnJzdnl9gYSGh4aFg398eXd
2d3l8foCChIaIh4aEgQA='''

sound_data = base64.b64decode(wav_base64)

app = wx.App(0)
# create a MyFrame instance and show the frame
MyFrame(None, 'wx.SoundFromData()', (300, 100), sound_data).Show()
app.MainLoop()
Votes + Comments
wonderful
Random rep for effort put in 'beginner' threads :)
0

I was doing a search on Daniweb for 'wx.AboutBox()', but it simply did not select a post, only the whole thread. So, this may be already somewhere. I am testing wxPython's fancy wx.AboutBox widget:

# testing the fancy wx.AboutBox() widget
# snee

import wx
from wx.lib.wordwrap import wordwrap

class MyFrame(wx.Frame):
    """
    create a frame, with a menu, statusbar and 2 about dialogs
    """
    def __init__(self):
        # create a frame/window, no parent, default to wxID_ANY
        wx.Frame.__init__(self, None, wx.ID_ANY, "wx.AboutBox test",
            pos=(300, 150), size=(300, 350))
        self.SetBackgroundColour("brown")

        # create a status bar at the bottom
        self.CreateStatusBar()
        self.SetStatusText("Click on File")

        menu = wx.Menu()
        # the optional & allows you to use alt/a
        # the last string argument shows in the status bar on mouse_over
        menu_about = menu.Append(wx.ID_ANY, "&About", "Ho-hum about box")
        menu_about2 = menu.Append(wx.ID_ANY, "About&2", "Fancy about box")
        menu.AppendSeparator()
        # the optional & allows you to use alt/x
        menu_exit = menu.Append(wx.ID_ANY, "E&xit", "Quit the program")

        # create a menu bar at the top
        menuBar = wx.MenuBar()
        # the & allows you to use alt/f
        menuBar.Append(menu, "&File")
        self.SetMenuBar(menuBar)

        # bind the menu events to an action/function/method
        self.Bind(wx.EVT_MENU, self.onMenuAbout, menu_about)
        self.Bind(wx.EVT_MENU, self.onMenuAbout2, menu_about2)
        self.Bind(wx.EVT_MENU, self.onMenuExit, menu_exit)

    def onMenuAbout(self, event):
        """a somewhat ho-hum about box"""
        dlg = wx.MessageDialog(self,
            "a simple application using wxFrame, wxMenu\n"
            "a statusbar, and this about message.",
            "About", wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    def onMenuAbout2(self, event):
        """use the much fancier wx.AboutBox()"""
        # first fill the info object
        info = wx.AboutDialogInfo()
        # Name and Version show in larger font
        info.Name = "Bratwurst7"
        info.Version = "v.1.7.4"
        info.Copyright = "(C) copyfight 2008"
        info.Description = wordwrap(
            "The Bratwurst7 program is a software program that "
            "makes you desire a freshly grilled bratwurst and "
            "a good German beer right now!  Teaching programmers "
            "everywhere to be aware of those hidden immediate "
            "inner desires!",
            300, wx.ClientDC(self))
        info.WebSite = ("http://en.wikipedia.org/wiki/Bratwurst",
            "Bratwurst7 home")
        info.Developers = ["Carl Arm", "Carol Bein", "Candy Kisser"]
        info.License = "Wish upon a star!"
        # now call wx.AboutBox with this info object
        wx.AboutBox(info)

    def onMenuExit(self, event):
        self.Close(True)


app = wx.App()
# create the MyFrame class instance, then show the frame
MyFrame().Show()
app.MainLoop()
0

This code shows how to create a custom pop-up dialog for text entry ...

# using wxPython's
# wx.Dialog(parent, id, title, pos, size, style, name="dialogBox")
# to create a custom text entry pop-up dialog
# vegaseat

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
        self.SetBackgroundColour("green")

        # call the dialog or input widget
        self.button = wx.Button(self, -1, label='Get the name', pos=(20, 20))
        # bind mouse or key event to an action
        self.button.Bind(wx.EVT_BUTTON, self.onAction)
        # create an output widget
        self.result = wx.TextCtrl(self, -1, value="", pos=(20, 70), 
            size=(200, 120), style=wx.TE_MULTILINE|wx.HSCROLL)        

    def onAction(self, event):
        """call the pop-up dialog and get the string entered"""
        dlg = MyDialog(self, 'Text Entry', 'Enter your name:')
        if dlg.ShowModal() == wx.ID_OK:
            # note, parent has been assigned dialog's entry instance
            self.name = self.entry.GetValue()
            self.result.AppendText(self.name + '\n')    
        dlg.Destroy()        


class MyDialog(wx.Dialog):
    def __init__(self, parent, mytitle, msg):
        wx.Dialog.__init__(self, parent, -1, mytitle, size=(250,180))
        entry = wx.TextCtrl(self, -1, value="", size=(200, 20))
        # assign dialog's entry instance to parent
        parent.entry = entry
        button_ok = wx.Button(self, wx.ID_OK)
        button_cancel = wx.Button(self, wx.ID_CANCEL)
        sizer =  self.CreateTextSizer('  ' + msg)
        sizer.Add(entry, 0, wx.ALL, 5)
        sizer.Add(button_ok, 0, wx.ALL, 5)
        sizer.Add(button_cancel, 0, wx.ALL, 5)
        self.SetSizer(sizer)
        

app = wx.App(0)
# create a MyFrame instance and show the frame
mytitle = 'custom entry dialog'
width = 300
height = 260
MyFrame(None, mytitle, (width, height)).Show()
app.MainLoop()
0

Here we use the simple wx.lib.filebrowsebutton.FileBrowseButton() to load and show an image ...

# experiment with wxPython's
# wx.StaticBitmap(parent, id=-1, bitmap, pos=wx.DefaultPosition, 
#     size=wx.DefaultSize, style=0, name="staticBitmap")
# wx.lib.filebrowsebutton.FileBrowseButton(parent, labelText,
#     fileMask)
# to load and show an image file
# the frame expands to show the entire image
# vegaseat

import wx
import wx.lib.filebrowsebutton as wxfbb

class MyFrame(wx.Frame):
    def __init__(self, parent, mysize):
        wx.Frame.__init__(self, parent, -1, size=mysize)
        self.panel = wx.Panel(self)
        self.size = mysize

        # file browser masked to look for common image types
        mask ="*.gif; *.jpg; *.png; *.bmp" 
        self.fbb = wxfbb.FileBrowseButton(self.panel,
            labelText="Select an image file:", fileMask=mask)
        self.button = wx.Button(self.panel, wx.ID_ANY, ">>  Show")
        self.button.Bind(wx.EVT_BUTTON, self.load_image)
        # setup the layout with sizers
        hsizer = wx.BoxSizer(wx.HORIZONTAL)
        hsizer.Add(self.fbb, 1, wx.ALIGN_CENTER_VERTICAL)
        hsizer.Add(self.button, 0, wx.ALIGN_CENTER_VERTICAL)
        # create a border space
        border = wx.BoxSizer(wx.VERTICAL)
        border.Add(hsizer, 0, wx.EXPAND|wx.ALL, 10)
        self.panel.SetSizer(border)

    def load_image(self, event):
        image_file = self.fbb.GetValue()
        # hide the file browse panel
        self.panel.Hide()
        
        image = wx.Bitmap(image_file)
        image_size = image.GetSize()
        # set the frame size to fit the image size
        self.SetClientSize(image_size)
        
        # bitmap's upper left corner is frame pos=(0, 0) by default
        wx.StaticBitmap(self, wx.ID_ANY, image, size=image_size)
        
        # optionally show some image information in the frame title
        width, height = image_size
        depth = image.GetDepth()
        info = "%s  %dx%dx%d" % (image_file, width, height, depth)
        self.SetTitle(info)
        

app = wx.App(0)
# create a MyFrame instance and show the frame
mysize = (600, 200)
MyFrame(None, mysize).Show()
app.MainLoop()
0

The wxPython wx.lib.fancytext.StaticFancyText() class can display colorful text written in XML format:

# wxPython's 
# wx.lib.fancytext.StaticFancyText(parent, id, text, ...)
# can display text written in XML format
# Henri

import  wx
import  wx.lib.fancytext as wxft

class FancyText(wx.Panel):
    def __init__(self, parent, xml_text):
        wx.Panel.__init__(self, parent, -1)
        self.ftext = wxft.StaticFancyText(self, -1, text=xml_text,
            background=wx.Brush('black'))
        

red = '<font family="swiss" color="red" size="48">'
blue = '<font family="swiss" color="blue" size="48">'
green = '<font family="swiss" color="green" size="48">'

# match the 3 <font ...> tags with closing </font> tags
xml_text = """\
%s     Feeling %sblue?
%s Or green with envy? 
</font>
</font>
</font>
""" % (red, blue, green)

app = wx.App(0)
mytitle = 'wx.lib.fancytext.StaticFancyText()'
mysize = (620, 220)
frame = wx.Frame(None, -1, title=mytitle, size=mysize)
FancyText(frame, xml_text)
frame.Show()
app.MainLoop()
0

Example of wx.ScrolledWindow to display large area in one small frame:

# test wx.ScrolledWindow(parent, id, pos, size, style)
# with multiple widgets that exceed normal frame area
# tested with Python 2.5.4 and wxPython 2.8.9.1
# Henri

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle):
        wx.Frame.__init__(self, parent, -1, mytitle, size=(400,300))

        # create scrolled window
        # let the wx.ScrolledWindow fill the frame
        self.scrollw = wx.ScrolledWindow(self, wx.ID_ANY)
        self.scrollw.SetBackgroundColour('green')
        # set EnableScrolling(bool x_scrolling, bool y_scrolling)
        # default is self.scrollw.EnableScrolling(True, True)
        # if True, wx.ScrolledWindow shows its scroll bars 
        # create the scroll bars, set the scrolling ranges (pixels)
        max_w = 1000
        max_h = 1000
        # SetScrollbars(pixelsPerUnitX, pixelsPerUnitY, noUnitsX, 
        #    noUnitsY)
        self.scrollw.SetScrollbars(20, 20, max_w//20, max_h//20)

        # pick something that needs area larger than the frame
        self.createMultiLabels()

    def createMultiLabels(self):
        """from one of vegaseat's example codes"""
        # things to put on the labels
        label_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ->UM'
        # wx.GridSizer(rows, cols, vgap, hgap)
        gsizer = wx.GridSizer(6, 5, 0, 0)
        # create list of labels
        # acccess with self.labels[0], self.labels[1] etc.
        self.labels = []
        for c in label_string:
            # labels have of scroll window as parent
            self.labels.append(wx.StaticText(self.scrollw, -1,
                label=c, style=wx.ALIGN_CENTRE|wx.SUNKEN_BORDER))
        # iterate through the list of labels and set 
        # layout, optionally font and colour
        font = wx.Font(60, wx.MODERN, wx.NORMAL, wx.BOLD)
        for x in self.labels:
            x.SetFont(font)
            x.SetBackgroundColour("yellow")
            gsizer.Add(x, 0, flag=wx.ALL, border=20)
        # set the sizer in scroll window
        self.scrollw.SetSizer(gsizer)


app = wx.App(0)
# create MyFrame instance and show the frame
MyFrame(None, "wx.ScrolledWindow for large display").Show()
app.MainLoop()
0

You can give your wxPython window nice custom icon:

# experiment with wxPython's wx.Icon() and SetIcon()

import wx

class MyFrame(wx.Frame):
    """make a frame, inherits wx.Frame"""
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'wxPython custom icon',
            pos=wx.Point(300, 150), size=wx.Size(300, 350))
        self.SetBackgroundColour('green')
        
        # pick icon file (.ico) you have ...
        #iconFile = "py.ico"
        # or 32x32 Windows .bmp file will do ...
        # (will miss mask if not rectangular image)
        icon_file = "Attention32x32.bmp"
        self.SetIcon(wx.Icon(icon_file, wx.BITMAP_TYPE_ICO))

        # show the frame
        self.Show(True)


application = wx.App(0)
# call class MyFrame
window = MyFrame()
application.MainLoop()
0

Hey Henri, thanks for reminding me that these multilables are a nice filler to force the scrollbars to show. Here I applied them to the scrolled panel ...

# exploring wxPython's
# wx.lib.scrolledpanel.ScrolledPanel(parent, id, pos, size, style)
# default pos is (0, 0) and default size is (-1, -1) which fills the frame
# the scrolled panel is an area on which other controls are placed
# that can take more space then the parent frame has

import wx
import wx.lib.scrolledpanel

class MyScrolledPanel(wx.lib.scrolledpanel.ScrolledPanel):
    def __init__(self, parent):
        # make the scrolled panel larger than its parent
        wx.lib.scrolledpanel.ScrolledPanel.__init__(self, parent, 
            wx.ID_ANY, size=(600, 600), style=wx.TAB_TRAVERSAL)
        # scroll bars won't appear until required
        # default is SetupScrolling(scroll_x=True, scroll_y=True)
        self.SetupScrolling()
        self.SetBackgroundColour("blue")

        # these multilabels will force the scroll bars to show
        # as they exceed the size of the frame
        label_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ #@$'
        # wx.GridSizer(rows, cols, vgap, hgap)
        gsizer = wx.GridSizer(6, 5, 0, 0)
        # create a list of labels
        # acccess with self.labels[0], self.labels[1] etc.
        self.labels = []
        for c in label_string:
            self.labels.append(wx.StaticText(self, wx.ID_ANY,
                label=c, style=wx.ALIGN_CENTRE))
        # iterate through the list of labels and set layout
        # font and colour
        font = wx.Font(24, wx.MODERN, wx.NORMAL, wx.BOLD)
        for x in self.labels:
            x.SetFont(font)
            x.SetBackgroundColour("yellow")
            gsizer.Add(x, 0, flag=wx.ALL|wx.EXPAND, border=15)
        # set the sizer
        self.SetSizer(gsizer)


app = wx.App(0)
# create a frame, no parent, default ID, title, size
caption = "ScrolledPanel"
frame = wx.Frame(None, wx.ID_ANY, caption, size=(250, 310))
MyScrolledPanel(frame)
frame.Center()
frame.Show()
app.MainLoop()
0

If the user of your program has to select from a fixed list of choices, the wx.SingleChoiceDialog is a good way to go:

# exploring the wx.SingleChoiceDialog
# fish_list from:
# http://allrecipes.com/Recipes/Seafood/Fish/Main.aspx
# snee

import wx

class MyFrame(wx.Frame):
    def __init__(self, fish_list):
        wx.Frame.__init__(self, None, -1, 'wx.SingleChoiceDialog',
            size=(350, 100))
        self.CreateStatusBar()
        label = wx.StaticText(self)
        
        dlg = wx.SingleChoiceDialog(None,
            "What's your favorite fish to eat?",
            'Select a Fish', fish_list)
        if dlg.ShowModal() == wx.ID_OK:
            answer = dlg.GetStringSelection()
            # show the selected choice different ways ...
            sf = 'Your choice was: %s' % answer
            label.SetLabel(sf)
            self.SetStatusText(sf)
            self.SetTitle(sf)
        dlg.Destroy()

fish_list = [
'Catfish',
'Cod',
'Flounder',
'Haddock',
'Halibut',
'Mahi Mahi',
'Salmon',
'Snapper',
'Swordfish',
'Tilapia',
'Trout',
'Tuna'
]

app = wx.App()
frame = MyFrame(fish_list)
frame.Center()
frame.Show()
app.MainLoop()
0

So you want to test drive some wxPython widgets without all that OOP stuff, here are some examples how to do this:

# test a wxPython combobox selection

import wx

def combo_select(event):
    color = combo.GetValue()
    frame.SetTitle(color)


app = wx.App(0)
frame = wx.Frame(None, -1, "wx.ComboBox", size=(220, 40))

# set up the choices for the listbox part of the combobox
choice_list = ['red', 'green', 'blue', 'yellow','white', 'magenta']
# create a combobox widget
combo = wx.ComboBox( frame, -1, choices=choice_list)
# set initial value
combo.SetValue('red')
# click on a dropdown choice to select it
combo.Bind(wx.EVT_COMBOBOX, combo_select)

frame.Center()
frame.Show()
app.MainLoop()

One more for the Gipper:

# test wxPython checkbox selections

import wx

def on_action(event):
    s = ""
    if cb1.IsChecked():
        s += "cb1 (red) is checked  "
    if cb2.IsChecked():
        s += "cb2 (blue) is checked  "
    if not cb1.IsChecked() and not cb2.IsChecked():
        s = "none is checked"
    frame.SetTitle(s)


app = wx.App(0)
frame = wx.Frame(None, -1, "wx.CheckBox", size=(450, 79))

cb1 = wx.CheckBox(frame, -1, 'red', pos=(10, 10))
cb2 = wx.CheckBox(frame, -1, 'blue', pos=(10, 40))
# set checkbox cb1 to checked
cb1.SetValue(True)
# bind checkbox mouse click to an action
cb1.Bind(wx.EVT_CHECKBOX, on_action)
cb2.Bind(wx.EVT_CHECKBOX, on_action)
# initial call
on_action(None)

frame.Center()
frame.Show()
app.MainLoop()

Edited by sneekula: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.