为了账号安全,请及时绑定邮箱和手机立即绑定

使用 TKinter 对象内部定义的图像按钮

使用 TKinter 对象内部定义的图像按钮

波斯汪 2021-08-17 18:15:48
我正在尝试构建一个tkinter带有图像作为对象内部背景的按钮。为什么第二个实现不起作用没有任何意义!这里有 3 个非常简单的例子;谁能解释为什么第二个实现不起作用?(Python 3.6.4 :: Anaconda, Inc.)1. 全局创建的按钮。奇迹般有效...from tkinter import *from PIL import Image, ImageTkfrom numpy import randomw = Tk()def cb():    print("Hello World")image = ImageTk.PhotoImage(image=Image.fromarray(random.random((50,50))))b = Button(w, text="text", command=cb, image=image)b.pack()w.mainloop()2. 在对象内部创建的A带有背景图像的按钮该按钮在单击时不起作用并且不显示图像:(。显然有问题,但我不明白......from tkinter import *from PIL import Image, ImageTkfrom numpy import randomw = Tk()class A():    def __init__(self, w):        image = ImageTk.PhotoImage(image=Image.fromarray(random.random((50,50))))        b = Button(w, text="text", command=self.cb, image=image)        b.pack()    def cb(self):        print("Hello World")a = A(w)w.mainloop()3.在对象内部创建的按钮,A没有背景图像该按钮工作正常,但我也想显示图像from tkinter import *from PIL import Image, ImageTkfrom numpy import randomw = Tk()class A():    def __init__(self, w):        image = ImageTk.PhotoImage(image=Image.fromarray(random.random((50,50))))        b = Button(w, text="text", command=self.cb)#, image=image)        b.pack()    def cb(self):        print("Hello World")a = A(w)w.mainloop()
查看完整描述

2 回答

?
PIPIONE

TA贡献1829条经验 获得超9个赞

我想我明白发生了什么。感谢链接的问题,在第二种情况下发生的事情是,image一旦__init__方法完成,您就会被垃圾收集。因此,根应用程序无法再使用您的图像,因此无法将其绑定到它。解决方法是将其设为类属性:


class A():

    def __init__(self, w):

        self.image = ImageTk.PhotoImage(image=Image.fromarray(random.random((50,50))))

        b = Button(w, text="text", command=self.cb, image=self.image)

        b.pack()


    def cb(self):

        print("Hello World")


查看完整回答
反对 回复 2021-08-17
?
莫回无

TA贡献1865条经验 获得超7个赞

你在这里有两个问题。


第一个问题是图像没有被保存__init__。您可能知道您需要保存对图像的引用,以便在 tkinter 中使用它。您可能不知道,在类中,如果您不将图像分配给类属性,则在__init__.


所以要解决第一个问题,你需要改变这个:


image = ImageTk.PhotoImage(image=Image.fromarray(random.random((50,50))))

对此:


# add self. to make it a class attribute and keep the reference alive for the image.

self.image = ImageTk.PhotoImage(image=Image.fromarray(random.random((50,50))))

您在这里可能没有注意到的第二个问题是加载图像时您的文本不会显示。这是因为您需要添加参数compound以便 tkinter 在按钮中显示图像和文本。也就是说,您还需要更新 image 参数以包含新的self.image.


所以改变这个:


b = Button(w, text="text", command=self.cb, image=image)

对此:


# added compound and change text color so you can see it.

b = Button(w, compound="center" , text="text", fg="white", command=self.cb, image=self.image)

结果:

//img1.sycdn.imooc.com//611b8c780001847401240092.jpg

查看完整回答
反对 回复 2021-08-17
  • 2 回答
  • 0 关注
  • 158 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信