【问题标题】:tkinter matplotlib error _tkinter.TclError: image "pyimage1" doesn't exist in Pycharmtkinter matplotlib 错误_tkinter.TclError:图像“pyimage1”在 Pycharm 中不存在
【发布时间】:2022-07-05 23:58:15
【问题描述】:

我正在尝试运行以下代码,它运行成功...但是当我尝试导入 matplotlib 时它给出错误----> _tkinter.TclError: image "pyimage1" doesn't exist while using PyCharm, 但是使用 python IDLE 它可以正常工作。

import cv2
from tkinter import *
from PIL import Image, ImageTk
import datetime
import openpyxl
#from matplotlib import pyplot as plt

def show_frames():
    im = cap.read()[1]
    Image1= cv2.cvtColor(im,cv2.COLOR_BGR2RGB)
    img = Image.fromarray(Image1)
    imgtk = ImageTk.PhotoImage(image = img)
    label.imgtk = imgtk
    label.configure(image=imgtk)
    label.after(20, show_frames)

def capture():
    I = cap.read()[1]
    save_name = str(datetime.datetime.now().today()).replace(":", " ") + ".jpg"
    cv2.imwrite(save_name, I)


 #here creating window and GUI
 win = Tk()
 win.geometry("1200x650")
 win.title('Portable Optical Spectrometer')

 L2 = Label(win,text = " Camera  ",font=("times new roman",20,"bold"),bg="white",fg="red").grid(row=0, column=0)
 L2 = Label(win,text = " Spectrum Graph ",font=("times new roman",20,"bold"),bg="white",fg="red").grid(row=0, column=2)
 label =Label(win)
 label.grid(row=1, column=0)
 cap = cv2.VideoCapture(0)

 show_frames()
 B1 = Button(win,text="Capture",font=("Times new roman",20,"bold"),bg="white",fg="red",command=capture()).grid(row=3, column=0, )
 B1 = Button(win,text="Analysis",font=("Times new roman",20,"bold"),bg="white",fg="red",).grid(row=4, column=0)

 L1 = Label(win,text = "Detected Material is:  ",font=("times new roman",20,"bold"),bg="white",fg="red").grid(row=4, column=1)
 Output = Text(win, height = 3,width = 25,bg = "light cyan").grid(row=4, column=2)


 win.mainloop()
 cap.release()

有人可以建议如何解决这个错误

【问题讨论】:

    标签: python matplotlib tkinter


    【解决方案1】:

    是的,PhotoImage 的文档记录很差,但似乎如果您有多个 Tkinter 根,那么您需要指定 PhotoImage 应该使用的 哪个 根 - 使用“master”参数。这适用于基本的 Tkinter PhotoImage 和 Pillow 的 ImageTk 包装器。 Matplotlib 通常使用 Tk 作为其后端,因此通常会引发问题。 IDLE 也使用 Tk,所以任何人都可以猜测这个组合会做什么。

    请参阅以下示例。如果从下面的两个 PhotoImage 创建行中的任何一个中删除“master=”参数,则会出错。

    import matplotlib
    matplotlib.use("TkAgg")
    
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    
    import tkinter as tk
    root = tk.Tk()
    
    photimg = tk.PhotoImage(width=100,height=100, master=root)
    tk.Label(root, image=photimg).pack()
    
    from PIL import Image, ImageTk
    pilimg = Image.new(mode="RGB", size=(200, 200))
    imgtk = ImageTk.PhotoImage(image=pilimg, master=root)
    tk.Label(root, image=imgtk).pack()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多