【问题标题】:matplotlib and Pillow (PIL) incompatible?matplotlib 和 Pillow (PIL) 不兼容?
【发布时间】:2018-08-28 14:27:36
【问题描述】:

如果我运行以下程序,我将无法运行:

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 会导致这个错误?

【问题讨论】:

    标签: python matplotlib tkinter python-imaging-library


    【解决方案1】:

    代码对我来说运行流畅,你的问题是pyimage10存储在内存中,但找不到路径,重新启动内核并清除内存中所有声明的变量将解决此问题。

    【讨论】:

    • 为什么会出现奇怪的格式?为什么你认为 OP 正在使用 Jupyter 或类似的东西(即他可以重新启动内核/清除所有声明的变量)
    • 你不需要 jupyter 来重新启动内核,我在 tkinter 中处理一个大项目时遇到过同样的问题无数次。这里的格式纯粹是因为对比度和更容易阅读,OP帖子中格式的原因是因为很难阅读错误消息,当我没有把它放在code标签中时它不允许我发布因为不幸的是我在这些标签之外有代码。 @FlyingTeller
    • 您对本文中的“内核”有何理解?
    • compiler @FlyingTeller 因为它是 spyder 中编译器的名称
    猜你喜欢
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多