2015-04-01 46 views
1

下面是代碼:如何根據GUI中的隨機值輸入獲取閃爍標籤?

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級編程的初學者。

回答

0

添加self.Refresh()來更新方法的末尾,以獲得靜態文本,以更新其背景色

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

非常感謝!精美的工作!這個函數到底做了什麼? – 2015-04-02 17:07:52