【问题标题】:Image on a button按钮上的图像
【发布时间】:2011-05-16 22:12:28
【问题描述】:

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

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

脚本 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()

脚本 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()

【问题讨论】:

    标签: python image button tkinter


    【解决方案1】:

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

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

    【讨论】:

    • 我被困在同一件事上,你的回答就像一个魅力。谢谢@BryanOakley!
    • 即使使用“self.photo...”也无法正常工作。区别可以是 Python 3 吗???
    • @rlinner:不,python 2 和 python 3 在图像方面没有任何变化。
    【解决方案2】:

    它的工作

    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)
    

    但这没用

    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()
    

    【讨论】:

      【解决方案3】:
      logo = PhotoImage(file = 'mine32.gif')
      small_logo = logo.subsample(5, 5)
      self.b.config(image = small_logo , compound = LEFT )
      

      【讨论】:

      • 为什么分配photo然后不使用呢?
      【解决方案4】:

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

      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)
      

      【讨论】:

        【解决方案5】:

        从 tkinter 导入 *

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-01-12
          • 1970-01-01
          • 1970-01-01
          • 2022-07-01
          • 1970-01-01
          • 2017-09-21
          相关资源
          最近更新 更多