Python 按钮上的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4297949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:08:54  来源:igfitidea点击:

Image on a button

pythonimagebuttontkinter

提问by coder

I expect the same output for both of the scripts below.

我希望以下两个脚本的输出相同。

But I don't get the image on the button when I execute Script 1. However, Script 2works well.

但是当我执行Script 1时,我没有在按钮上看到图像。但是,脚本 2运行良好。

Script 1

脚本 1

from Tkinter import *
  class fe:
    def __init__(self,master):
      self.b=Button(master,justify = LEFT)
      photo=PhotoImage(file="mine32.gif")
      self.b.config(image=photo,width="10",height="10")
      self.b.pack(side=LEFT)
root = Tk()
front_end=fe(root)
root.mainloop()

Script 2

脚本 2

from Tkinter import *
root=Tk()
b=Button(root,justify = LEFT)
photo=PhotoImage(file="mine32.gif")
b.config(image=photo,width="10",height="10")
b.pack(side=LEFT)
root.mainloop()

采纳答案by Bryan Oakley

The only reference to the image object is a local variable. When __init__exits, the local variable is garbage collected so the image no is destroyed. In the second example, because the image is created at the global level it never goes out of scope and is therefore never garbage collected.

对图像对象的唯一引用是局部变量。当__init__退出时,被当作垃圾回收的局部变量,因此图像没有被破坏。在第二个示例中,因为图像是在全局级别创建的,所以它永远不会超出范围,因此永远不会被垃圾收集。

To work around this, save a reference to the image. For example, instead of photouse self.photo

要解决此问题,请保存对图像的引用。例如,而不是photo使用self.photo

回答by Bryan Oakley

its work

这是工作

x1=Button(root)
photo=PhotoImage(file="Re.png")
x1.config(image=photo,width="40",height="40",activebackground="black"
,bg="black", bd=0,command=sil)
x1.place(relx=1,x=5, y=-5, anchor=NE)

but this is useless

但这没用

def r():
    x1=Button(root)
    photo=PhotoImage(file="Re.png")
    x1.config(image=photo,width="40",height="40",activebackground="black",
    bg="black", bd=0,command=sil)
    x1.place(relx=1,x=5, y=-5, anchor=NE)

r()

回答by Saurabh Chandra Patel

logo = PhotoImage(file = 'mine32.gif')
small_logo = logo.subsample(5, 5)
self.b.config(image = small_logo , compound = LEFT )

回答by Mawty

from tkinter import *

从 tkinter 导入 *

root= Tk()

btnPlay = Button(root)
btnPlay.config(image=imgPlay, width="30", height="30")
btnPlay.grid(row=0, column=0)

root.mainloop()

回答by nda

Unrelated answer, but this is the answer I was looking for when I first came here. Use this to resize the image before adding it to the button.

不相关的答案,但这是我第一次来到这里时正在寻找的答案。在将图像添加到按钮之前使用它来调整图像的大小。

from PIL import Image, ImageTk

image = Image.open("path/to/image.png")
image = image.resize((25, 25), Image.ANTIALIAS)
self.reset_img = ImageTk.PhotoImage(image)
self.button = tk.Button(frame, image=self.reset_img)