ttk / Python

时间:2017-01-25 23:06:46

标签: 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__(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上找到herehere以及用户的示例的合并。

提前感谢任何想法/见解。

-Sean

1 个答案:

答案 0 :(得分:3)

PhotoImagegarbage collector有问题,如果将图像分配给局部变量,则会删除该图像。

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

self.buttonPhoto = ImageTk.PhotoImage(buttonImage) 

全:

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

        # use self.buttonPhoto
        self.buttonPhoto = ImageTk.PhotoImage(buttonImage) 

        # use self.buttonPhoto
        myButton = ttk.Button(self, image=self.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()

或者将图像分配给其他对象 - 它也应该停止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()

请参阅页面末尾The Tkinter PhotoImage Class

Note