Skip to main content
 首页 » 编程设计

python之为什么此代码不接受此 png 图像透明度

2025年05月04日15dflying

我已经将问题的原因隔离为图像,因为代码似乎可以与其他透明的 png 图像一起使用。但是,它似乎不适用于我需要的一张图片。当我试图制作一个形状漂亮的 window 时,这会很有帮助。

图片:

代码:

import wx 
 
class PictureWindow(wx.Frame): 
    def __init__(self, parent, id, title, pic_location): 
 
        # For PNGs. Must be PNG-8 for transparency... 
        self.bmp = wx.Image(pic_location, wx.BITMAP_TYPE_PNG).ConvertToBitmap() 
 
        framesize = (self.bmp.GetWidth(), self.bmp.GetHeight()) 
 
        # Launch a frame the size of our image. Note the position and style stuff... 
        # (Set pos to (-1, -1) to let the OS place it. 
        # This style wx.FRAME_SHAPED is a frameless plain window. 
        wx.Frame.__init__(self, parent, id, title, size=framesize, pos = (50, 50), style = wx.FRAME_SHAPED) 
 
        r = wx.RegionFromBitmap(self.bmp) 
        self.SetShape(r) 
 
        # Define the panel and place the pic 
        panel = wx.Panel(self, -1) 
        self.mainPic = wx.StaticBitmap(panel, -1, self.bmp) 
 
        # Set an icon for the window if we'd like 
        #icon1 = wx.Icon("icon.ico", wx.BITMAP_TYPE_ICO) 
        #self.SetIcon(icon1) 
 
        self.Show() 
 
        # The paint stuff is only necessary if doing a shaped window 
        self.Bind(wx.EVT_PAINT, self.OnPaint) 
        self.Main() 
 
 
    def OnPaint(self, event): 
        dc = wx.PaintDC(self) 
        dc.DrawBitmap(self.bmp, 0, 0, True) 
 
    def Main(self): 
        sizer = wx.GridBagSizer() 
        button = wx.Button(self,-1,label="Click me !") 
        sizer.Add(button, (0,1)) 
 
 
# What pic are we opening? 
pic_location = r"C:\Users\user\Pictures\CPUBAR\A4.png" # PNG must be png-8 for             transparency... 
 
app = wx.App(redirect=0) # the redirect parameter keeps stdout from opening a wx gui window 
PictureWindow(None, -1, 'Picture Viewer', pic_location) 
app.MainLoop() 

这是在 Windows 7 中,顺便说一句。

请您参考如下方法:

wx.RegionFromBitmap 使用位图的掩码来设置形状。如果您的源图像有 alpha channel ,那么它就没有 mask ,因此 wx.RegionFromBitmap 将无法确定要使用的形状。您可以转换源图像,使所有像素完全不透明或完全透明,然后 wx.Image 将使用 mask 而不是 alpha channel 加载它。或者您可以在将其转换为 wx.Bitmap 之前使用 wx.Image 的 ConvertAlphaToMask 方法在运行时对其进行转换。