以下是代码:
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级别编程的初学者。
添加一个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()