微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python tkinter,在画布上调整透明图像的大小

如何解决Python tkinter,在画布上调整透明图像的大小

我正在使用 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 所说的标签。工作方式非常不干净,并创建未使用的标签来存储变量以防止移动到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,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),image=image,tag="map")
                    cur_label.image = image
                    del cur_label  # attempt to clean up the code slightly
                cur_x += 1
            cur_y += 1

感谢您的帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。