python-使用通过TKinter在对象内部定义的图像按钮

我正在尝试使用对象内部的背景图像来构建tkinter按钮.为什么第二种实现不起作用没有任何意义!

这是3个非常简单的例子;谁能解释第二种实施不起作用的原因?

(Python 3.6.4 :: Anaconda,Inc.)

1.全局创建的按钮.

奇迹般有效…

from tkinter import *
from PIL import Image, ImageTk
from numpy import random
w = 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, ImageTk
from numpy import random
w = 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, ImageTk
from numpy import random
w = 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()

解决方法:

我想我明白发生了什么.由于存在链接问题,第二种情况是__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")
上一篇:linux学习第一周


下一篇:Tkinter模块学习