Python In Action:三、再来一个扩展例子,保证不难

在窗口显示一张图片,代码如下:

 1 import wx
 2 
 3 class Frame(wx.Frame):
 4     """Frame class that displays an image."""
 5 
 6     def __init__(self, image, parent=None, id=-1,
 7                  pos=wx.DefaultPosition, title='Hello, wxPython!'):
 8         """Create a Frame instance and display image."""
 9         temp = image.ConvertToBitmap()
10         size = temp.GetWidth(), temp.GetHeight()
11         wx.Frame.__init__(self, parent, id, title, pos, size)
12         self.bmp = wx.StaticBitmap(parent=self, bitmap=temp)
13         self.SetClientSize(size)
14 
15 class App(wx.App):
16     """Application class."""
17 
18     def OnInit(self):
19         image = wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG)
20         self.frame = Frame(image)
21         self.frame.Show()
22         self.SetTopWindow(self.frame)
23         return True
24 
25 def main():
26     app = App()
27     app.MainLoop()
28 
29 if __name__ == '__main__':
30     main()

运行结果:

自定义的App,其他的不用说,之前的篇章讲过:只是有一句新的写法:

image = wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG)
看过代码的人,就能猜到了,定义一个图片对象,格式JPEG。

在Frame里:
 temp = image.ConvertToBitmap()
在组件上显示的位图图像,所以要转换成位图.
 size = temp.GetWidth(), temp.GetHeight()
得到图像的宽、高,这种写法很新颖,可以多学学,返回一个tuple
 self.bmp = wx.StaticBitmap(parent=self, bitmap=temp)
自然就是图像组件了(不然硬盘里的图像没法绘制在窗口上)。这里,我比较注重的是它的参数,parnet=self意思是父窗口为Frame,
这样就自动包含在了Frame中


self.SetClientSize(size)
最后,将窗口大小设置成图片大小

打完收工!

下一篇:小小总结



原文地址:https://www.cnblogs.com/cool-fire/p/4158873.html