我正在用python和Tkinter库做一个等距游戏。不过,在将我的原理图渲染到屏幕上时,我遇到了一个问题。我似乎不能保持透明的背景,即使图像(.png)被存储为pil中的rgba。当我保存图像时,就在加载之前;它们仍然有一个透明的背景,所以这与我调整图像大小的方式有关。我看了看周围,我看到的大多数答案都是说编辑pil插件,或者实际上没有调整图像的大小。有没有一种相对简单的方法来调整图像大小并保持透明度,而不包括摆弄pil插件??
我的代码:
def renderToTkCanvas(self, x_axis, y_axis, cv, block_width=50, block_height=50):
cur_schem = self._map_schematic.getSchematic()
cur_y = 0
for y in cur_schem:
cur_x = 0
for x in y:
if x != 0:
image = ImageTk.PhotoImage(x.resize((block_width, block_height)))
cur_label = Label(image=image)
cv.create_window(x_axis + (block_width * cur_x), y_axis + (block_height * cur_y), window=cur_label, anchor="nw", tag="map")
cur_label.image = image
cur_x += 1
cur_y += 1使用的原理图(1x4):
[[<PIL.Image.Image image mode=RGBA size=1170x1240 at 0x12F5AFC9C10>], [<PIL.Image.Image image mode=RGBA size=1170x1240 at 0x12F5AFC9C10>], [<PIL.Image.Image image mode=RGBA size=1169x1240 at 0x12F5AFDED60>], [<PIL.Image.Image image mode=RGBA size=1170x1240 at 0x12F5AFC9C10>]]Thx需要任何帮助:)
发布于 2021-04-02 20:39:47
好了,我设法找到了问题所在。正如@jasonharper所说,问题不在于调整大小,而在于标签。这种工作方式非常不干净,并且创建未使用的标签来存储变量,以防止移动到python垃圾。我尝试过数组/列表,但似乎不起作用,代码如下。我不认为将来会有很多人遇到这个问题,因为它太小了,但我也会把工作代码放在下面。
使用不起作用的列表的代码:
def renderToTkCanvas(self, x_axis, y_axis, cv, block_width=50, block_height=50):
cur_schem = self._map_schematic.getSchematic()
img_matrix = []
cur_y = 0
for y in cur_schem:
cur_x = 0
img_matrix.append([])
for x in y:
if x != 0:
image = ImageTk.PhotoImage(image=x.resize((block_width, block_height)))
img_matrix[cur_y].append(image)
cv.create_image(x_axis + (block_width * cur_x / 2), y_axis + (block_height * cur_y / 2), image=img_matrix[cur_y][cur_x], anchor="nw", tag="map")
else:
img_matrix[cur_y].append(0)
cur_x += 1
cur_y += 1可以工作但非常不干净的代码:
def renderToTkCanvas(self, x_axis, y_axis, cv, block_width=50, block_height=50):
cur_schem = self._map_schematic.getSchematic()
cur_y = 0
for y in cur_schem:
cur_x = 0
for x in y:
if x != 0:
image = ImageTk.PhotoImage(image=x.resize((block_width, block_height)))
cur_label = Label(image=image)
cv.create_image(x_axis + (block_width * cur_x / 2), y_axis + (block_height * cur_y / 2), image=image, anchor="nw", tag="map")
cur_label.image = image
del cur_label # attempt to clean up the code slightly
cur_x += 1
cur_y += 1谢谢你的帮助。
https://stackoverflow.com/questions/66907537
复制相似问题