【问题标题】:Putting gif image in tkinter window将 gif 图像放入 tkinter 窗口
【发布时间】:2016-07-29 13:47:19
【问题描述】:

单击按钮时,我试图在新的 tkinter 窗口中插入 gif 图像,但我不断收到此错误

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\idlelib\run.py", line 119, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\queue.py", line 172, in get
raise Empty
queue.Empty

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:/Users/Afro/Desktop/mff.py", line 8, in sex
canvas = tkinter.Label(wind,image = photo)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2605, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2138, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage1" doesn't exist

这是代码。图片和位置确实存在。

import tkinter

def six():
    wind = tkinter.Tk()
    photo = tkinter.PhotoImage(file = 'American-Crime-Story-1.gif')
    self = photo
    canvas = tkinter.Label(wind,image = photo)
    canvas.grid(row = 0, column = 0)

def base():
    ssw = tkinter.Tk()
    la = tkinter.Button(ssw,text = 'yes',command=six)
    la.grid()
base()

我做错了什么?

【问题讨论】:

  • 我在您的代码中没有看到对pyimage1 的引用?
  • 如果我打印出照片变量,它会显示pyimage1 而不是<tkinter.PhotoImage object at 0x000001DE4D2A2B38>

标签: python python-3.x tkinter


【解决方案1】:

您正在尝试创建Tk 窗口的两个实例。你不能这样做。如果你想要第二个窗口或弹出窗口,你应该使用Toplevel() 小部件。

另外,self 在这种情况下没有任何意义。使用小部件的图像属性会更好to keep a reference

import tkinter

ssw = tkinter.Tk()

def six():
    toplvl = tkinter.Toplevel() #created Toplevel widger
    photo = tkinter.PhotoImage(file = 'American-Crime-Story-1.gif')
    lbl = tkinter.Label(toplvl ,image = photo)
    lbl.image = photo #keeping a reference in this line
    lbl.grid(row=0, column=0)

def base():
    la = tkinter.Button(ssw,text = 'yes',command=six)
    la.grid(row=0, column=0) #specifying row and column values is much better

base()

ssw.mainloop()

【讨论】: