将gif图像放入tkinter窗口

时间:2016-07-29 13:47:20

标签: python python-3.x tkinter

我点击按钮时尝试在新的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()

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您正在尝试创建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()