PhotoImage与garbage collector有问题,如果图像被分配给局部变量,它会删除图像。在
将image赋值给类变量self.buttonPhotoself.buttonPhoto = ImageTk.PhotoImage(buttonImage)
完整:
^{pr2}$
或者将图像分配给其他对象-它也应该停止garbage collector。在
也就是说myButton.image = buttonPhoto
完整:from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
class Example(ttk.Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master)
master.title('Button Test')
self.configure(padding='10 10 10 10')
self.grid(column=0, row=0, sticky=(N, E, W, S))
buttonImage = Image.open('tplay.png')
buttonPhoto = ImageTk.PhotoImage(buttonImage)
myButton = ttk.Button(self, image=buttonPhoto, padding='10 10 10 10')
myButton.grid(column=1, row=1, sticky=(E, W))
# assign image to other object
myButton.image = buttonPhoto
if __name__ == "__main__":
root = Tk()
example = Example(root)
root.mainloop()