2012-07-19 30 views
1

的繼承的一個之外創建一個類中的staticBitmap我的應用程序的結構如下:如何wx.Frame

class GameWindow(wx.Frame): 
    imageFile = r"C:\Users\Trufa\Desktop\pyll\img\ball.png" 
    data = open(imageFile, "rb").read() 
    stream = cStringIO.StringIO(data) 
    bmp = wx.BitmapFromImage(wx.ImageFromStream(stream)) 
    image = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap() 
    self.ball = wx.StaticBitmap(self, -1, image, (0, 0), (image.GetWidth(), image.GetHeight())) 
    self.ball.Center() 

if __name__ == '__main__':  
    app = wx.App() 
    GameWindow(None, title='Pyll') 
    app.MainLoop() 

這簡化版本按預期工作創造了球,然後圍繞它。

現在,我已經嘗試了所有種類的東西,但不能得到各地要怎麼解決如下:我想創造球和它在一個單獨的類中的方法,就像這樣:

class Ball: 
    #Code to make the ball 
    def move(self): 
     self.ball.Center() 

第一這是一個很好的方法o我應該儘量保持在GameWindow課程中,我想我會從將Ball概念抽象爲課程中受益。

而且無論如何,這怎麼能做到。我確信球類必須從某人身上繼承,但我不確定是誰。

我試圖從GameWindowwx.Frame沒有什麼好結果繼承,但我不知道如果我做一些觀念性錯誤的或者被編程錯了,是不是能夠做到這一點對我的知識缺乏的編程類和OO一般在python中。

綜上所述,我想是這樣的:

class Ball():#What should I inherit from? 
    imageFile = r"C:\Users\Trufa\Desktop\pyll\img\ball.png" 
    data = open(imageFile, "rb").read() 
    stream = cStringIO.StringIO(data) 
    bmp = wx.BitmapFromImage(wx.ImageFromStream(stream)) 
    image = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap() 
    self.ball = wx.StaticBitmap(self, -1, image, (0, 0), (image.GetWidth(), image.GetHeight())) 
    def move(self): 
     self.ball.Center() 

回答

1

你真正需要做的是子類wx.StaticBitmap。至少,這是我對你想要做的事情的理解。這裏有一個簡單的例子:

import wx 

######################################################################## 
class Ball(wx.StaticBitmap): 
    """""" 

    #---------------------------------------------------------------------- 
    def __init__(self, parent, imageFile): 
     """Constructor""" 
     wx.StaticBitmap.__init__(self, parent=parent) 
     image = wx.Image(imageFile, wx.BITMAP_TYPE_ANY) 
     self.SetBitmap(wx.BitmapFromImage(image)) 
     self.Center() 


######################################################################## 
class GamePanel(wx.Panel): 
    """""" 

    #---------------------------------------------------------------------- 
    def __init__(self, parent): 
     """Constructor""" 
     wx.Panel.__init__(self, parent) 

     sizer = wx.BoxSizer(wx.VERTICAL) 
     self.ball = Ball(self, "ball.png") 
     sizer.Add(self.ball, 0, wx.ALL|wx.CENTER, 5) 
     self.SetSizer(sizer) 

######################################################################## 
class GameWindow(wx.Frame): 

    #---------------------------------------------------------------------- 
    def __init__(self, title): 
     """""" 
     wx.Frame.__init__(self, None, title=title, size=(400,400)) 
     panel = GamePanel(self) 
     self.Show() 


#---------------------------------------------------------------------- 
if __name__ == '__main__':  
    app = wx.App() 
    GameWindow('Pyll') 
    app.MainLoop() 
相關問題