Tkinter:将具有透明背景的图像添加到按钮

问题描述

希望你们一切都好。我有一个问题,希望您能提供帮助。

我正在尝试在tkinter中建立一个棋盘游戏。这将具有不同形状的图块,这些图块被放置在背景图像顶部的正方形中。我设法使用tk.PhotoImage和tk.Label添加了背景,并使用ImageTk.PhotoImage正确调整了图块的大小。

但是,当我将瓷砖放置在板上时,所有的透明度都消失了,取而代之的是单调灰色。

enter image description here

最小代码:

from PIL import Image,ImageTk
import tkinter as tk

def tile_push():
    pass

# Create background image
root = tk.Tk()
root.geometry("390x500") # Size of background board
background_image = tk.PhotoImage(file="Gameboard.png")
background_label = tk.Label(root,image=background_image)
background_label.place(x=0,y=0,relwidth=1,relheight=1)

# Create button
im = Image.open("Chick.png").resize((100,100))
image_player_1 = ImageTk.PhotoImage(im)
b = tk.Button(root,image=image_player_1,command=tile_push,borderwidth=0,highlightthickness=0)
b.place(x=140,y=258,width=115,height=115)
tk.mainloop()

关于SO的类似问题表明如何将背景设置为黑色,但是我需要背景是透明的。

任何帮助将不胜感激!

解决方法

感谢支持acw,我现在设法解决了这个问题。这就是我所做的:

from PIL import Image,ImageTk
import tkinter as tk

def tile_push(*args,**kwargs):
    print("It's alive!")

# Create background image
root = tk.Tk()
root.geometry("390x500") # Size of background board
canvas = tk.Canvas(root,width=390,height=500)
canvas.place(x=0,y=0)
background_image = tk.PhotoImage(file="Gameboard.png")
canvas.create_image((0,0),anchor="nw",image=background_image)

# Create button
im = Image.open("Chick.png").resize((115,115))
imTk =  ImageTk.PhotoImage(im)
chick = canvas.create_image((140,258),image=imTk)
canvas.tag_bind(chick,'<Button-1>',tile_push)
tk.mainloop()

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...