我正在构建一个小型 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/