如何根据GUI中的随机值输入获得闪烁的标签?

时间:2015-04-01 09:20:48

标签: wxpython

以下是代码:

import wx      
import random      
import time        
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="BATTERY")
    self.flashingText.SetFont(self.font)

    self.timer = wx.Timer(self)
    self.Bind(wx.EVT_TIMER, self.update, self.timer)
    self.timer.Start(2000)

#----------------------------------------------------------------------
def update(self, event):
    """"""

    x=random.uniform(1,10)
    print(x)
    if x>5:
       self.flashingText.SetBackgroundColour('red')


    else:
        self.flashingText.SetBackgroundColour('white')
class MyFrame(wx.Frame):
    """ok"""

#----------------------------------------------------------------------

    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()
    time.sleep(2)
    app.MainLoop()

即使逻辑看似合理,代码也无法正常工作。如果可以,请更正此问题!

PS:请耐心等待,我是wxPython和GUI级编程的初学者。

1 个答案:

答案 0 :(得分:0)

在update方法的末尾添加一个self.Refresh()以获取statictext来更新其背景颜色

import wx
import random


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="BATTERY")
        self.flashingText.SetFont(self.font)

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.update, self.timer)
        self.timer.Start(2000)

    def update(self, event):
        """"""

        x = random.uniform(1, 10)
        print(x)
        if x > 5:
            self.flashingText.SetBackgroundColour('red')

        else:
            self.flashingText.SetBackgroundColour('white')

        self.Refresh()


class MyFrame(wx.Frame):

    """ok"""

    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()