目前正在使用
WXpython
创建一个国际象棋益智游戏,我正在尝试显示 2 个图像,一个在另一个之上。
问题是,尽管我的文件中白色棋子的原始图像具有透明背景,但所有透明像素似乎都转换为白色并遮挡了后面显示的图像。
我不想只在棋盘上创建一张棋子图像,因为那会非常乏味。
如果图像在
wxpython
中透明,我是否可以将背景设为透明?
boardIMG = "chessboard.PNG"
self.board_img = wx.Image(boardIMG, wx.BITMAP_TYPE_PNG).Rescale(500,500).ConvertToBitmap()
wx.StaticBitmap(self, -1, self.board_img, (0, 0), (self.board_img.GetWidth(), self.board_img.GetHeight()))
WpawnIMG = "Wpawn.PNG"
self.Wpawn_img = wx.Image(WpawnIMG, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
wx.StaticBitmap(self, -1, self.Wpawn_img, (0,0), (self.Wpawn_img.GetWidth(), self.Wpawn_img.GetHeight()))
我尝试使用Python Pillow来改变像素颜色, 使用
EVT_PAINT
和 mask,因为我在这里看过类似的问题,但没有找到有同样问题的人。
wxPython 的 StaticBitmap 控件的透明度支持似乎与平台相关。或多或少使用你的确切代码和我从维基百科获得的这两个图像:
import wx
class MainWindow(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(500, 500))
boardIMG = "chessboard.png"
self.board_img = wx.Image(boardIMG, wx.BITMAP_TYPE_PNG).Rescale(500,500).ConvertToBitmap()
wx.StaticBitmap(self, -1, self.board_img, (0, 0), (self.board_img.GetWidth(), self.board_img.GetHeight()))
WpawnIMG = "whitepawn.png"
self.Wpawn_img = wx.Image(WpawnIMG, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
wx.StaticBitmap(self, -1, self.Wpawn_img, (0,0), (self.Wpawn_img.GetWidth(), self.Wpawn_img.GetHeight()))
app = wx.App()
frame = MainWindow(None, -1, "Window")
frame.Show(1)
app.MainLoop()
我在 Linux 和 Windows 上分别得到了以下结果:
使其在 Windows 上也能工作的一个简单方法是按如下方式处理 OnPaint:
import wx
class MainWindow(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(500, 500))
boardIMG = "chessboard.png"
self.board_img = wx.Image(boardIMG, wx.BITMAP_TYPE_PNG).Rescale(500,500).ConvertToBitmap()
WpawnIMG = "whitepawn.png"
self.Wpawn_img = wx.Bitmap(WpawnIMG) # can just use instead of the line below
#self.Wpawn_img = wx.Image(WpawnIMG, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
self.Bind(wx.EVT_PAINT, self.OnPaint)
def OnPaint(self, evt):
dc = wx.PaintDC(self)
# draw the board first
dc.DrawBitmap(self.board_img, 0, 0)
# then the pieces
for i in range(3):
# image, horizontal pos, vertical pos
dc.DrawBitmap(self.Wpawn_img, i * 150, 0)
app = wx.App()
frame = MainWindow(None, -1, "Window")
frame.Show(1)
app.MainLoop()
在更新坐标后更新屏幕,这样您的屏幕不会比使用 StaticBitmap 控件复杂多少。