Image 将图像添加到按钮中
在学习tkinter的过程中,我遇到了一个问题:我无法将图像添加到按钮中:Image 将图像添加到按钮中,image,python-3.x,tkinter,photoimage,Image,Python 3.x,Tkinter,Photoimage,在学习tkinter的过程中,我遇到了一个问题:我无法将图像添加到按钮中: from tkinter import* from tkinter import ttk root=Tk() button=ttk.Button(root) button.grid() photo=PhotoImage(file="giphy.gif") button.config(image=photo, compound=RIGHT) root.mainloop() 该代码会出错: <ipython-i
from tkinter import*
from tkinter import ttk
root=Tk()
button=ttk.Button(root)
button.grid()
photo=PhotoImage(file="giphy.gif")
button.config(image=photo, compound=RIGHT)
root.mainloop()
该代码会出错:
<ipython-input-30-6ad3ebb78b5b> in <module>()
7 button.grid()
8 photo=PhotoImage(file="giphy.gif")
----> 9 button.config(image=photo, compound=RIGHT)
10
11 root.mainloop()
/usr/lib/python3.5/tkinter/__init__.py in configure(self, cnf, **kw)
1331 the allowed keyword arguments call the method keys.
1332 """
-> 1333 return self._configure('configure', cnf, kw)
1334 config = configure
1335 def cget(self, key):
/usr/lib/python3.5/tkinter/__init__.py in _configure(self, cmd, cnf, kw)
1322 if isinstance(cnf, str):
1323 return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf)))
-> 1324 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
1325 # These used to be defined in Widget:
1326 def configure(self, cnf=None, **kw):
TclError: image "pyimage.." doesn't exist
()
7按钮网格()
8 photo=PhotoImage(file=“giphy.gif”)
---->9 button.config(图像=照片,化合物=右侧)
10
11 root.mainloop()
/配置中的usr/lib/python3.5/tkinter/_init__.py(self,cnf,**kw)
1331允许的关键字参数调用方法键。
1332 """
->1333返回自配置('configure',cnf,kw)
1334 config=configure
1335 def cget(自动,钥匙):
/usr/lib/python3.5/tkinter/__init___;u.py in_uconfigure(self、cmd、cnf、kw)
1322如果存在(cnf、str):
1323返回self._getconfigure1(_展平((self._w,cmd,'-'+cnf)))
->1324自我测试调用(_flatten((自我测试,命令))+自我测试选项(cnf))
1325#这些过去在小部件中定义:
1326 def配置(自身,cnf=无,**kw):
Tcl错误:映像“pyimage..”不存在
为什么会这样?我该如何修复它呢?正如furas在评论中所说,您的代码完全可以通过
python script.py运行
错误来自于您在Jupyter QtConsole中运行它的事实。
为了能够在Jupyter QtConsole中运行它,您需要明确地告诉tkinter什么是PhotoImage
的父窗口。我认为这是因为在控制台中,默认父窗口不是您创建的Tk
实例,而是某个隐藏窗口。因此,图像的父窗口不是按钮的父窗口,因此tkinter找不到图像
应在控制台中运行以下代码:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
button = ttk.Button(root)
button.grid()
photo = tk.PhotoImage(file="giphy.gif", master=root)
button.config(image=photo, compound=tk.RIGHT)
错误与代码不匹配。请修复。我对其进行了测试,该代码对我来说运行良好。向我们展示一些复制错误的代码。其他tkinter组件(如标签)也存在相同的错误。您是否在jupyter QtConsole中运行此错误?问题可能是PhotoImage和垃圾收集器的错误,当图像分配到本地时,它们会从内存中删除图像变量。请参见第页的注释。在控制台python script.py
中正常运行此代码,而不是在python的shell中运行。