ttk/Python中的按钮图像问题

ttk/Python中的按钮图像问题,python,tkinter,python-3.5,imagebutton,ttk,Python,Tkinter,Python 3.5,Imagebutton,Ttk,我在Python(3.5)中处理ttk/tkinter,我在按钮(特别是ttk.Button)方面遇到了一些问题 无论我尝试什么,我都无法在按钮上显示我一生的图像 我有以下代码: from tkinter import * from tkinter import ttk from PIL import Image, ImageTk class Example(ttk.Frame): def __init__(self, master): ttk.Frame.__init

我在Python(3.5)中处理ttk/tkinter,我在按钮(特别是ttk.Button)方面遇到了一些问题

无论我尝试什么,我都无法在按钮上显示我一生的图像

我有以下代码:

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('play.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))

if __name__ == "__main__":
    root = Tk()
    example = Example(root)
    root.mainloop()
这是我找到的示例和StackOverflow上用户提供的示例的合并

提前感谢您的任何想法/见解


-Sean

PhotoImage
与垃圾收集器存在问题,垃圾收集器在将图像分配给局部变量时会删除图像

将图像分配给类变量
self.buttonPhoto

self.buttonPhoto = ImageTk.PhotoImage(buttonImage) 
全部:

或者将图像分配给其他对象-它也应该停止垃圾收集器

全部:



请参见第页末尾的
注释
PhotoImage
垃圾收集器有问题,如果将图像分配给局部变量,垃圾收集器会删除图像

将图像分配给类变量
self.buttonPhoto

self.buttonPhoto = ImageTk.PhotoImage(buttonImage) 
全部:

或者将图像分配给其他对象-它也应该停止垃圾收集器

全部:



请参阅第页末尾的
注释

PhotoImage
垃圾收集器有问题,如果将图像分配给局部变量,垃圾收集器会删除图像。将图像分配给类变量
self。按钮photo
PhotoImage
垃圾收集器有问题,垃圾收集器将图像分配给局部变量后删除。将图像分配给执行该操作的类变量
self.buttonPhoto
。非常好的信息,也解释了我引用的一个例子的一部分。谢谢,furas。这很有效,但我有个问题。我在谷歌上搜索了很多参考资料,但没有找到ttk.Button的选项填充。为什么它在这里工作?你能再解释一下吗?谢谢,成功了。非常好的信息,也解释了我引用的一个例子的一部分。谢谢,furas。这很有效,但我有个问题。我在谷歌上搜索了很多参考资料,但没有找到ttk.Button的选项填充。为什么它在这里工作?你能再解释一下吗?谢谢
    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()