[英]Python tkinter, resizing transparent image on canvas
我正在使用 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>]]
感謝任何幫助:)
好的,所以我設法找到了問題所在。 正如@jasonharper 所說,問題不在於調整大小,而在於 label。 工作方式非常不干凈,並創建未使用的標簽來存儲變量以防止移動到 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
感謝您的幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.