using time.sleep in wxPython

2019-07-24 03:03发布

问题:

Using time.sleep in my wxPython code just after re-positioning a bitmapbutton caused my button to go totally blank. Just a white space was left in the region where the button should have been. Can any one please explain the reason and suggest any solution? Here's my code:

import wx
import time
class gui(wx.Frame):
  def __init__(self,parent,id):
    wx.Frame.__init__(self,parent,id,'New Window',pos=(0,0),size=wx.DisplaySize())
    panel=wx.Panel(self)
    self.SetBackGroundColour('green')
    self.pic=wx.BitmapButton(self,-1,wx.Image("Candle.jpg",wx.BITMAP_TYPE_ANY).ConvertToBitmap(),pos=(700,300))
    self.Bind(wx.EVT_BUTTON,self.position,self.pic)
  def positon(self,event):
    self.pic.Hide()
    self.pic=wx.BitmapButton(self,-1,wx.Image("Candle.jpg",wx.BITMAP_TYPE_ANY).ConvertToBitmap(),pos=(700,300))
    time.sleep(2)
    self.pic.Hide()
if __name__=='__main__':
  app=wx.PySimpleApp()
  frame=gui(None,-1)
  frame.Show()
  app.MainLoop()

回答1:

time.sleep() blocks wx's mainloop and makes the GUI unresponsive for however long you've told it to sleep. There are several alternatives. You can use a wx.Timer or use threads (or similar). I think using a Timer makes more sense in your use case though.



回答2:

Well there's no wonder your button goes blank, you've pretty much programmed it to do so.

    self.pic.Hide() => hides the button
 self.pic=wx.BitmapButton(self,-1,wx.Image("Candle.jpg",wx.BITMAP_TYPE_ANY).ConvertToBitmap(),pos=(700,300)) => displays the button once again
    time.sleep(2) => takes a brake for 2 seconds
    self.pic.Hide() => hides the button again

The conclusion is, your button won't show up. So I don't see what's the problem, as it does exactly what you programmed it to.



回答3:

well it depends, was time sleep used in the button's event ?, cause I believe if it was it's because of that. The button waits for the event it triggered to end so it would go back to its initial state.



回答4:

sleep is blocking, so execution is stuck in your position method for two seconds and is unable to return to the MainLoop to process other events, like painting your changes to the screen. After the two seconds are up the image is hidden, but was never drawn.

To get the effect you want you'll have to start a timer, and bind the timer to a handler which can show the StaticBitmap again.

By the way you can also call Show again rather than creating a new control, and it's parent should also be the panel, not the frame.