我如何正确使用标签在 tkinter 中显示图像,因为每次打开窗口时都会显示图像,但它看起来完全是白色的,没有显示其相关内容?
我有这样的疑惑,因为下面代码中使用的图片格式是PNG,图片是透明的,内容是纯色的,但是运行代码后,只出现全白标签。有关更多有用的信息,我将这段代码称为刽子手游戏的初始阶段,有问题的图像存储在变量 image2 中,这是发生错误的地方。在这种情况下不会调用变量 image1。
from tkinter import *
from tkinter import ttk
root = Tk()
root.configure(background="#4F4F4F")
root.option_add('*tearOff', False)
def images():
image1 = PhotoImage(file='Boneco1.png')
image1 = image1.subsample(1, 3)
image2 = PhotoImage(file="Bonecolindo.png")
image2 = image2.subsample(1, 1)
return [image1, image2]
class Game:
def __init__(self):
root.title("TWG")
root.geometry("900x700")
label = ttk.Label(root, text="The Words Game", font=("Times New Roman", 18), background="#4F4F4F", foreground="white")
label.place(relx=0.5, y=30, anchor="center")
image = Label(root, image=images()[0], borderwidth=2, relief="solid", bg="gray")
image.place(x=0, rely=0.5, anchor="center")
imagel = Label(root, image=images()[1])
imagel.place(relx=0.5, rely=0.5, anchor="center")
Game()
root.mainloop()
1- 我已经将图像重新格式化为各种兼容格式,现在我使用的是 PNG 格式。
2- 我使用图像编辑器 GIMP,为图像背景创建了一个 alpha 通道。我尝试多次重新编写代码,将图像变量从
images()
函数中取出并将其放入 init()
函数中,但同样的事情发生了。
3-我已经试过修改图片,我也测试了其他几张图片,看看是不是文件的问题,但还是出现了其他问题。
我正在使用一个特定的库,所以我希望除非有必要,否则不必使用另一个库。