image - 将图像按钮添加到顶级窗口 Tkinter

标签 image python-2.7 tkinter

我正在构建一个小型 GUI 应用程序,一旦单击按钮,就会打开一个新的顶级窗口,并且它应该显示按钮的图像。

我可以让图像按钮在根窗口上工作,但不能在顶层窗口上工作。只出现一个黑匣子。

我在两个窗口上都有一个通用按钮,并且它们确实有效。

我是 Python 新手。

import Tkinter 
from Tkinter import *
from PIL import ImageTk, Image

root = Tkinter.Tk()

root.title("First Window")                  
root.configure(background = "black")    

def new_window():
    win2 = Toplevel(root)
    win2.geometry("650x350+50+40")        
    win2.title("Second Window!")            
    win2.configure(background = "white")    

    def close1():
        win2.destroy()

    img1 = ImageTk.PhotoImage(Image.open("./images/close.gif"))
    c1 = Button(win2, image = img1, bg ="black", command = close1)
    c1.grid(row = 1)

    c2= Tkinter.Button(win2, text='close', command = close1)
    c2.grid(row = 2)    


nw = Tkinter.Button(root, text = 'New Window' , command = new_window)
nw.grid(row = 1)

def close3(): 
    root.destroy()

img3 = ImageTk.PhotoImage(Image.open("./images/close.gif"))
c3 = Button(root, image = img3, bg ="black", command = close3)
c3.grid(row = 2)


root.mainloop()

最佳答案

当您创建新的顶层时,您将使用局部变量来引用图像。因此,当该方法退出时,垃圾收集器将删除该图像。您需要将引用保存在全局变量中,或者以其他方式保护它免受垃圾收集器的影响

保存引用的常见方法是使其成为按钮的属性:

img1 = ImageTk.PhotoImage(...)
c1 = Button(...)
c1.image = img1

关于image - 将图像按钮添加到顶级窗口 Tkinter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17819338/

相关文章:

html - 加载 GIF(预加载器)仅在 Chrome 上卡住 - 另一个观点

html - 将 <div> 与包装上的图像重叠

python-2.7 - 如何识别从今天(包括今天)到过去和 future (不包括周末)的三个工作日并将它们放入 Pandas 数据框中?

python - Python 中的计数和分组

python - 如何使用 python 在 tkinter 中更改按钮和框架的字体和大小?

image - 计算图像中每行的像素数

JavaFX 图像空指针异常

python - 如何在 Python 中使用 .writerow() 进行切片

python - 当我将标签关联到 Tkinter 框架背景时,它会消失

python - 如何设置仅将某些字符输入到条目小部件中