简体   繁体   English

图像未显示在按钮上 Tkinter

[英]Image does not show on button Tkinter

I'm trying to simply add an image to a tkinter button.我试图简单地将图像添加到 tkinter 按钮。 I tried everything:我尝试了一切:

import tkinter as tk


root = tk.Tk()
root.geometry('300x300+300+150')
photo = tk.PhotoImage('home.gif')
btn = tk.Button(root, image = photo, width = 100, height = 100)
btn.image = photo  # even with this does not work
btn.pack()
root.mainloop()

I also tried with PIL setting the photo variable equal to ImageTk.PhotoImage(Image.open('home.gif')) , I tried easly the open function, the absolute path of the photo (and yes, the photo is inside the same directory of my script), but anything works.我还尝试使用 PIL 将photo变量设置为ImageTk.PhotoImage(Image.open('home.gif')) ,我很容易尝试open function,照片的绝对路径(是的,照片在同一个我脚本的目录),但一切正常。 The window just pop up with a big button, without image inside. window 只是弹出一个大按钮,里面没有图像。

UPDATE: I tried with other images, and I noticed that some images are shown while others no.更新:我尝试使用其他图像,我注意到显示了一些图像,而另一些则没有。 This is because the images with transparent background cause a bug or a problem to tkinter... so, I do not know if there's a way to solve this.这是因为透明背景的图像会导致 tkinter 出现错误或问题...所以,我不知道是否有办法解决这个问题。 On google I find out that some people use canvas but I actually need the image to be inside the button so I do not know how to do.在谷歌上我发现有些人使用 canvas 但我实际上需要图像在按钮内所以我不知道该怎么做。

Please change your code as below请更改您的代码如下

photo = tk.PhotoImage(file='home.gif')

because i changed the above code and it worked....因为我更改了上面的代码并且它有效......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM