People keep on asking fun wxPython questions on StackOverflow. Today they wanted to know how to make “flashing text” in wxPython. That’s actually a pretty easy thing to do. Let’s take a look at some simple code:

import random
import time
import wx
 
########################################################################
class MyPanel(wx.Panel):
    """"""
 
    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
 
        self.font = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
        self.flashingText = wx.StaticText(self, label="I flash a LOT!")
        self.flashingText.SetFont(self.font)
 
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.update, self.timer)
        self.timer.Start(1000)
 
    #----------------------------------------------------------------------
    def update(self, event):
        """"""
        now = int(time.time())
        mod = now % 2
        print now
        print mod
        if mod:
            self.flashingText.SetLabel("Current time: %i" % now)
        else:
            self.flashingText.SetLabel("Oops! It's mod zero time!")
        colors = ["blue", "green", "red", "yellow"]
        self.flashingText.SetForegroundColour(random.choice(colors))
 
 
########################################################################
class MyFrame(wx.Frame):
    """"""
 
    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Flashing text!")
        panel = MyPanel(self)
        self.Show()
 
#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

Basically all you need is a wx.StaticText instance and a wx.Timer. In this example, the text will “flash” once a second. By flash, we mean it will change colors AND the text itself will change. The original person who made this question wanted to know how to display the time using Python’s time.time() method and they wanted the message to change depending on whether or not the modulus of the time by 2 was equal to zero. I realize that looks a little odd, but I’ve actually used that idea in some of my own code. Anyway, this worked for me on Windows 7 with Python 2.6.6 and wxPython 2.8.12.1.

Note that sometimes the SetForegroundColour method doesn’t work on all widgets across all platforms as the native widget doesn’t always allow the color to be changed, so your mileage may vary.