[英]matplotlib and Pillow (PIL) incompatible?
我有以下程序,如果我運行該程序將不起作用:
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會導致此錯誤?
代碼對我來說運行順利,您的問題是pyimage10存儲在內存中,但是找不到路徑,重新啟動內核並清除內存中所有已聲明的變量將解決此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.