当我使用 ImageTk 时,我的图像不透明

ImageTk我正在尝试使用和将图像放入窗口中PhotoImage。下面是代码:


import tkinter as tk

import random as r

from PIL import ImageTk, Image



window = tk.Tk()


HEIGHT = window.winfo_screenwidth()

WIDTH = window.winfo_screenheight()

RESOL = str(str(HEIGHT) + "x" + str(WIDTH+7) + "+" + str(-7) + "+" + str(0))

window.geometry(RESOL)


x = int(HEIGHT)/2

y = int(WIDTH)/2

updatex = HEIGHT + (0.6 * HEIGHT)


main = tk.Frame(window, height = WIDTH, width = HEIGHT)

main.configure(bg = "white", highlightthickness = 0)

main.place(x = x, y = y, anchor = "center")


Map = tk.Canvas(window, height = int((900 - int(x))) + int(900), width = int((900 - int(y))) + int(900), bg = "#44b863", highlightthickness = 0)

Map.place(x = updatex, y = int(y), anchor = "center")


p = tk.PhotoImage(file = "TitleForGameReal.png")

play_solo_image = tk.PhotoImage(file = "PlaySoloButton.png")

play_duo_image = tk.PhotoImage(file = "PlayDuoButton.png")


title = tk.Label(main, image = p, highlightthickness = 0, bd = 0)

title.place(relx = 0.5, rely = 0.35, anchor = "center")


class CustomButton:

    def __init__(self, image, master, height, width, bordercolor):

        self.master = master

        self.frame = tk.Frame(master, height = height, width = width, highlightthickness = 0)

        self.image = tk.Label(self.frame, image = image, borderwidth = 0, bg = "dark grey")

        self.bordercolor = bordercolor

    def put(self, x, y, command):

        self.x, self.y = x, y

        self.frame.place(relx = x, rely = y, anchor = "center")

        self.image.pack()


        def enter(event = "<Enter>"):

            self.image.config(borderwidth = 3)

        self.image.bind("<Enter>", enter)


        def leave(event = "<Leave>"):

            self.image.config(borderwidth = 0)

        self.image.bind("<Leave>", leave)

        def bind_command(event = "<Button-1>"):

            command()

        self.image.bind("<Button -1>", bind_command)

我还将留下图像作为参考,因为我在 PhotoShop 中编辑了照片以严格使其具有透明背景:

https://img.mukewang.com/64e41aed0001317802040155.jpg

潇湘沐
浏览 147回答 1
1回答

森林海

问题是需要一个 PhotoImage 实例image的选项Map.create_image(updatex, y, image = self.image),但你给它一个标签,所以要修复它只需说。class Player:&nbsp; &nbsp; def __init__(self, hp, image):&nbsp; &nbsp; &nbsp; &nbsp; self.hp = hp&nbsp; &nbsp; &nbsp; &nbsp; self.image = image #creating an instance variable&nbsp; &nbsp; &nbsp; &nbsp; self.pic = ImageTk.PhotoImage(self.image) #making an photoimage instance&nbsp; &nbsp; &nbsp; &nbsp; self.cv = Map.create_image(updatex, y, image = self.pic) #passing the photo image instance&nbsp; &nbsp; &nbsp; &nbsp; self.pic.image = self.pic #keeping a reference to the image希望这已经解决了错误,如果有任何错误或疑问,请告诉我。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python