wxPython 移动控件

0 投票
1 回答
1104 浏览
提问于 2025-04-18 12:25

我刚开始学习wxPython,现在我想用定时器让静态文本可以移动,但我遇到一个问题,就是当新的文本出现时,之前的文本并没有隐藏起来。

我在想几个可能的原因:

(1) 是不是因为我使用的是静态文本?也许换成其他控件就可以“移动”了?

(2) 当我想用“隐藏”或者“销毁”这些方法时,系统提示“未定义”。

如果有任何有用的建议就太好了,下面是我的代码(python版本:2.6):

#!/user/bin/python

import wx

pos_st = [[10,50],[40,50],[70,50],[100,50]]
i = -1

class Frame(wx.Frame):

    def __init__(self,parent,id):
        wx.Frame.__init__(self, parent, id,
                          'Move widget',
                          size = (200,150),
                          style=wx.MINIMIZE_BOX | wx.RESIZE_BORDER 
    | wx.SYSTEM_MENU | wx.CAPTION |  wx.CLOSE_BOX)
        self.initUI()

    def initUI(self):

        self.widgetPanel=wx.Panel(self, -1)
        self.widgetPanel.SetBackgroundColour('white')

        # Buttons for play the simulation
        playButton = wx.Button(self.widgetPanel, -1, "Play", pos=(10,10), size=(30,30))

        self.Bind(wx.EVT_BUTTON, self.play, playButton)
        playButton.SetDefault()

    def play(self, event):
        self.timer = wx.CallLater(1000, self.run_st)

    def run_st(self):
        global i
        i = (i+1)%4
        self.timer.Restart(1000)
        self.sT = wx.StaticText(self.widgetPanel, -1, '1',
                              pos=pos_st[i], size=(20,20))
        self.sT.SetBackgroundColour('grey')

if __name__ == "__main__":
    app = wx.App(False)
    frame = Frame(parent=None,id=-1)
    frame.Show()
    app.MainLoop()

1 个回答

1

StaticText中的“静态”其实和移动或者可变性没有关系,从用户的角度来看,它是静态的(也就是说用户不能改变它)。

def run_st(self):
    global i
    i = (i+1)%4
    self.timer.Restart(1000)
    if not hasattr(self,"sT"):
        self.sT = wx.StaticText(self.widgetPanel, -1, '1', size=(20,20))
        self.sT.SetBackgroundColour('grey')
    self.sT.SetPosition(pos_st[i])

这是因为你并没有改变现有文本的位置,而是每次都在创建一个新的文本...这样的话,你只是移动了已有的文本...不过其实你应该使用一个真正的计时器。

def initUI(self):

    self.widgetPanel=wx.Panel(self, -1)
    self.widgetPanel.SetBackgroundColour('white')

    # Buttons for play the simulation
    playButton = wx.Button(self.widgetPanel, -1, "Play", pos=(10,10), size=(30,30))

    self.Bind(wx.EVT_BUTTON, self.play, playButton)
    playButton.SetDefault()
    self.sT = wx.StaticText(self,-1,"",size=(20,20))
    self.timer = wx.Timer()
    self.timer.Bind(wx.EVT_TIMER,self.run_st)
def play(self, event):
    self.timer.Start(1000)

def run_st(self,timerEvent):
    global i
    i = (i+1)%4
    self.sT.SetLabel("1")
    self.sT.SetPosition(pos_st[i])

撰写回答