Python Tkinter .jpeg图像不显示 - TclError

时间:2015-10-23 21:04:40

标签: python image class tkinter canopy

我试图在我的GUI中添加.jpeg图像,同时还有其他几个小部件。

使用我的代码,当我使用以下命令时,我可以在单独的Tkinter窗口中显示图像:

#self.label = Label(image = self.img)

但是,每当我尝试将图像添加到原始Tkinter窗口时,我都会在代码下面看到错误。我尝试将其添加到原始Tkinter窗口的方式是:

#self.label = Label(frame, image = self.img)

复制错误

奇怪的是,当我尝试在较短版本的代码中复制错误时(例如直接在下面),它可以工作。然而!要在缩短的代码中复制错误,首先需要创建不同的错误。示例:将text = "Try"替换为text = "%s" %yikes(因为没有变量yikes它会给您一个错误)。将代码更改回之前的确切方式后,它会产生我在下面(TclError: image "pyimage__" doesn't exit)描述的错误。在最底层,我已经包括整个课程,因为我很难一直复制这个问题。我使用的是Python 2.7和Canopy 1.5.5。

缩短代码:

import matplotlib.pyplot as plt
from Tkinter import *
from PIL import ImageTk, Image
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
from tkFileDialog import askopenfilename, askdirectory

class App:

    def __init__(self, master):
        frame = Frame(master)

        self.button_left = Button(frame,text="< Previous Event")
        self.button_left.grid(row=1,column=0)
        self.button_right = Button(frame,text="Next Event >")
        self.button_right.grid(row=1,column=3)

       #Creating text for the UI indicating the number of leakage events
        w = Label(frame, text="Trying to Recreate error")
        w.grid(row=1,column=2)

        self.m = Canvas(frame,width=50,height=25)
        self.text_id = self.m.create_text(25,12.5, text="Try")
        self.m.grid(row=1,column=1)


        self.path = "C:\Carbonite\EL_36604.02_231694\EL_36604.02_231694_2015-06-15 10.39.57.jpeg"
        self.image = Image.open(self.path)
        self.img = ImageTk.PhotoImage(self.image)
        #self.label = Label(image = self.img)
        self.label = Label(frame,image = self.img)
        self.label.image = self.img
        self.label.grid(row = 3, column = 0)
        frame.grid(row=0,column=0)

root = Tk()
app = App(root)
root.mainloop()

当我使用注释掉的方法时,我在程序中收到错误:

    TclError                                  Traceback (most recent call last)
C:\Carbonite\Main_interface_file.py in <module>()
    136 
    137 root = Tk()
--> 138 app = App(root)
    139 root.mainloop()
    140 

C:\Carbonite\Main_interface_file.py in __init__(self, master)
     72         self.img = ImageTk.PhotoImage(self.image)
     73         #self.label = Label(image = self.img)
---> 74         self.label = Label(frame,image = self.img)
     75         self.label.image = self.img
     76         self.label.grid(row=3, column = 0)

C:\Users\U10596\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.5.3123.win-x86_64\lib\lib-tk\Tkinter.pyc in __init__(self, master, cnf, **kw)
   2585 
   2586         """
-> 2587         Widget.__init__(self, master, 'label', cnf, kw)
   2588 
   2589 class Listbox(Widget, XView, YView):

C:\Users\U10596\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.5.3123.win-x86_64\lib\lib-tk\Tkinter.pyc in __init__(self, master, widgetName, cnf, kw, extra)
   2084                 del cnf[k]
   2085         self.tk.call(
-> 2086             (widgetName, self._w) + extra + self._options(cnf))
   2087         for k, v in classes:
   2088             k.configure(self, v)

TclError: image "pyimage8" doesn't exist 

几乎整个代码:

import matplotlib.pyplot as plt
from Tkinter import *
from PIL import ImageTk, Image
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
from images_to_list import images_to_list
from tkFileDialog import askopenfilename, askdirectory
#Creating a class that creates the UI
class App:

    def __init__(self, master):

        self.event_num = 1
        # Create a container
        frame = Frame(master)

        # Create 2 buttons (changes between leakage events
        self.button_left = Button(frame,text="< Previous Event",
                                        command=self.decrease)
        self.button_left.grid(row=1,column=0)
        self.button_right = Button(frame,text="Next Event >",
                                        command=self.increase)
        self.button_right.grid(row=1,column=3)

       #Creating text for the UI indicating the number of leakage events
        w = Label(frame, text="/  %s  " % len(tft))
        w.grid(row=1,column=2)

        #Display the number of the current event in the series
        self.m = Canvas(frame,width=50,height=25)
        self.text_id = self.m.create_text(25,12.5, text="%s" % (self.event_num+1))
        self.m.grid(row=1,column=1)

        #Creating the plot of voltage data
        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)
        self.fig.autofmt_xdate()
        import matplotlib.dates as mdates
        self.ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
        self.line, = self.ax.plot(tft[self.event_num],tf1[self.event_num],'.')
        self.line2, = self.ax.plot(tft[self.event_num],tf2[self.event_num],'.')
        self.ax.set_ylim([0,3.5])


        self.path = "C:\Carbonite\EL_36604.02_231694\EL_36604.02_231694_2015-06-15 10.39.57.jpeg"
        self.image = Image.open(self.path)
        self.img = ImageTk.PhotoImage(self.image)
        #self.label = Label(image = self.img)
        self.label = Label(frame,image = self.img)
        self.label.image = self.img
        self.label.grid(row=3, column = 0)


        self.canvas = FigureCanvasTkAgg(self.fig,master=master)
        self.canvas.show()
        self.canvas.get_tk_widget().grid(row=1,column=0)
        frame.grid(row=0,column=0)

        #Creating a textbox to jump to event number
        self.textbox = Entry(frame,width=5)
        button1 = Button(frame, text='Go', command=self.letsgo) #Linking "Go" button with letsgo function to jump to event number
        self.textbox.grid(row=2,column=1)
        button1.grid(row=2,column=2)

    #function letsgo allows the user to jump to any event in the series    
    def letsgo(self):
        txt = self.textbox.get()
        try:
            self.event_num = int(txt)
        except ValueError:
            print "Opps! The number you enter needs to be an integer!"
        self.line.set_xdata(tft[self.event_num])
        self.line.set_ydata(tf1[self.event_num])
        self.line2.set_xdata(tft[self.event_num])
        self.line2.set_ydata(tf2[self.event_num])
        self.ax.set_xlim([min(tft[self.event_num]),max(tft[self.event_num])])
        self.canvas.draw()
        self.m.itemconfig(self.text_id, text="%s" % (self.event_num+1))

     #function decrease allows the user to use the decrease button                
    def decrease(self):
        if self.event_num == 0: #if statement accounts for if the user tries to see the event previous to the first one
            self.event_num = len(tft)-1
        else:
            self.event_num -= 1
        self.line.set_xdata(tft[self.event_num])
        self.line.set_ydata(tf1[self.event_num])
        self.line2.set_xdata(tft[self.event_num])
        self.line2.set_ydata(tf2[self.event_num])
        self.ax.set_xlim([min(tft[self.event_num]),max(tft[self.event_num])])
        self.canvas.draw()
        self.m.itemconfig(self.text_id, text="%s" % (self.event_num+1))

    #function increase allows the user to use the increase button            
    def increase(self):
        if self.event_num == len(tft)-1: #if statement accounts for if the user tries to see the event after the last one.
            self.event_num = 0
        else:
            self.event_num += 1        
        self.line.set_xdata(tft[self.event_num])
        self.line.set_ydata(tf1[self.event_num])
        self.line2.set_xdata(tft[self.event_num])
        self.line2.set_ydata(tf2[self.event_num])
        self.ax.set_xlim([min(tft[self.event_num]),max(tft[self.event_num])])
        self.canvas.draw()
        self.m.itemconfig(self.text_id, text="%s" % (self.event_num+1))





root = Tk()
app = App(root)
root.mainloop()

2 个答案:

答案 0 :(得分:0)

您需要对Frame进行网格化。当我添加

frame.grid()

__init__方法的底部,它可以正常工作。但是,当我运行您发布的代码时,我不会收到错误。它只是没有显示标签。我想知道这是否是一些依赖平台的行为。我在Yosemite 10.10.5上使用python 2.7。

编辑:我已经尝试了你的扩展示例,正如预期的那样,我没有看到你的行为。我可以来回更改代码。如果不正确,我会收到错误;如果它是正确的,它运行正常。

您描述的行为必须与Canopy有关。 python解释器的工作方式,它会在每次运行时将脚本编译为字节码;它对于脚本曾经说过的内容一无所知。

您可以尝试从命令行运行可疑脚本吗?此外,您可能应该在问题中添加canopy标记。

我不会使用Canopy,所以我不认为我可以帮助你,但我在这里留下答案作为有希望的人的背景。

祝你好运。

答案 1 :(得分:0)

我找到了问题!!

我在代码的最开头使用了askopenfilename(),这会打开一个额外的Tkinter窗口。结果,有两个Tkinter窗口打开并混淆了程序。

通过将所有内容发送到创建的第一个Tk窗口(并删除第二个窗口),它解决了问题。