I'm exporting a png with transparent background: enter image description here This is how it looks when it's exported: enter image description here and this is how it is displayed in Tkinter: enter image description here

我的代码是:

import tkinter as tk
import tkinter.ttk as ttk
from PIL import Image, ImageTk
import customtkinter

root = tk.Tk()
root.geometry("800x480")
root.resizable(False, False)
background_black = ImageTk.PhotoImage(file="background_black.png")
turn_on = ImageTk.PhotoImage(file="turn_on.png")

tk.Label(root, image=background_black).pack()

button = tk.Button(root, image=turn_on, borderwidth=0, highlightthickness=0, relief=tk.FLAT)
button.place(relx=0.5, rely=0.5, anchor=tk.CENTER)

root.mainloop()

原本应该是透明的区域却变成了白色,我该如何解决这个问题? 我提供了前2张图片,以防我在出口时做错了什么,而不是在我的代码中.

推荐答案

使用tkinter.Canvas():

import tkinter as tk

def img_button_press(*args, **kwargs):
    print("Pressed")

root = tk.Tk()
root.geometry("512x512") 
root.resizable(False, False)

canvas = tk.Canvas(root, width=512, height=512)
canvas.place(x=0,y=0)
background_image = tk.PhotoImage(file="bg.png")
canvas.create_image((255,255), anchor="center", image=background_image)

btn_img = tk.PhotoImage(file="img.png")
btn = canvas.create_image((255,255), anchor="center", image=btn_img)
canvas.tag_bind(btn, '<Button-1>', img_button_press)
tk.mainloop()

当然,如果需要,您可以使用PIL来调整图像,但如果您拥有与需要的图像完全相同的图像,则不需要这样做:

Img.png:

enter image description here

Bg.png:

enter image description here

似乎奏效了:

enter image description here

Python相关问答推荐

在应用循环中间保存pandas DataFrame

如果索引不存在,pandas系列将通过索引获取值,并填充值

在函数内部使用eval(),将函数的输入作为字符串的一部分

线性模型PanelOLS和statmodels OLS之间的区别

如何在具有重复数据的pandas中对groupby进行总和,同时保留其他列

为什么sys.exit()不能与subproccess.run()或subprocess.call()一起使用

为什么默认情况下所有Python类都是可调用的?

pandas:排序多级列

如何根据一列的值有条件地 Select 前N组?

pandas在第1列的id,第2列的标题,第3列的值,第3列的值?

joblib:无法从父目录的另一个子文件夹加载转储模型

numpy.unique如何消除重复列?

用两个字符串构建回文

Django Table—如果项目是唯一的,则单行

比较两个有条件的数据帧并删除所有不合格的数据帧

在一个数据帧中,我如何才能发现每个行号是否出现在一列列表中?

使用xlsxWriter在EXCEL中为数据帧的各行上色

.awk文件可以使用子进程执行吗?

Match-Case构造中的对象可调用性测试

两个名称相同但值不同的 Select 都会产生相同的值(discord.py)