我有以下程序,如果我运行该程序将不起作用:
import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image, ImageTk
##MATPLOTLIB STUFF --------------------------------------------
fig, ax = plt.subplots(figsize = (5,5))
x = np.arange(10)
y = np.random.randn(10)
ax.plot(x,y)
fig.savefig('image1.png', bboxtoinches = 'tight')
##PIL STUFF --------------------------------------------------
root = tk.Tk()
graph = ImageTk.PhotoImage(file="image1.png")
w1 = tk.Label(root, image=graph).pack(side='right')
explanation = "A matplotlib plot"
w2 = tk.Label(root, justify=tk.LEFT, padx=10,
text=explanation).pack(side='left')
root.mainloop()
但是如果我删除了matplotlib东西并运行
,它可以工作import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image, ImageTk
##PIL STUFF --------------------------------------------------
root = tk.Tk()
graph = ImageTk.PhotoImage(file="image1.png")
w1 = tk.Label(root, image=graph).pack(side='right')
explanation = "A matplotlib plot"
w2 = tk.Label(root, justify=tk.LEFT, padx=10,
text=explanation).pack(side='left')
root.mainloop()
事实上,似乎引起问题的那一行是
fig, ax = plt.subplots(figsize = (5,5))
如果我包括这一行,则会出现以下错误:
Traceback (most recent call last):
File "proj_1_images.py", line 20, in <module>
w1 = tk.Label(root, image=graph).pack(side='right')
File "C:\Users\Luke Polson\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 2760, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\Luke Polson\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 2293, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage10" doesn't exist
为什么matplotlib会导致此错误?
答案 0 :(得分:-1)
代码对我来说运行顺利,您的问题是pyimage10存储在内存中,但是无法找到路径,重新启动内核并清除内存中所有已声明的变量将解决此问题。