首页 > 解决方案 > TclError:图像不存在 - Tkinter 多窗口 python

问题描述

在我被要求查看其他主题之前,我只想说我拥有并且所有解决方案都涉及调用 atk.Toplevel()而不是tk.TK()或者在同一个 .py 文件中。我已经尝试过了(可能通过替换HAS(tk.Tk).HAS(tk.Toplevel)

TclError: image "brand_logo.png" doesn't exist我的代码中出现错误。我正在开发一个带有一些窗口的 Tkinter 软件,供用户浏览。每个窗口都会有一组问题需要回答。为了便于维护,我在不同的文件中开发了每个窗口,这样我就可以跟踪更容易的错误和对窗口本身的更改。

我的窗口创建类的代码是:

import tkinter as tk, Questions1 as q1, Questions2 as q2
class HAS(tk.Tk):    
def __init__(self, *args, **kwargs):
    tk.Tk.__init__(self, *args, *kwargs)
    #Page configure
    tk.Tk.wm_title(self, "Checklist")
    container = tk.Frame(self)
    container.pack(side="top", fill="both", expand=True)
    container.grid_rowconfigure(0, weight=1)
    container.grid_columnconfigure(0, weight=1)
    container.configure(background = "white")

    #Adding overhead menu
    menubar = tk.Menu(container)
    filemenu = tk.Menu(menubar, tearoff = 0)
    filemenu.add_command(label = "Save", command = self.saveList)
    filemenu.add_command(label = "Exit", command= self.destroy)
    menubar.add_cascade(label="File", menu=filemenu)
    tk.Tk.config(self, menu=menubar)

    #Defining the page_frames
    self.frames = {}
    for F in (q1.Q1, q2.Q2):
        frame = F(container, self)
        self.frames[F] = frame
        frame.grid(row=0, column=0, sticky="nsew")
    self.show_frame(q1.Q1)

#showing the selected frame              
def show_frame(self, cont):
    frame = self.frames[cont]
    frame.tkraise()

# Function accessing the list of answers
def saveList(self):
    dict_answers={'Answers 1': self.frames[q1.Q1].list_answers, "Answers 2": self.frames[q2.Q2].list_answers}
    print(dict_answers)

app = HAS() 
app.geometry("530x700")
app.mainloop()

我的每份问卷都遵循相同的结构,只是改变了文本和问题:

class Q1(tk.Frame):
def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    self.columnconfigure(0, minsize=100)
    self.columnconfigure(1, minsize=150)
    self.columnconfigure(2, minsize=50)     
    Logo = tk.PhotoImage("brand_logo.png")
    #Header Config
    tk.Frame.configure(self, background = "white")
    ttk.Label(self, image=Logo, background="white").grid(row=0, column=0, padx=100, columnspan=3, pady=10, sticky="W")
    ttk.Label(self, text="1st Checklist", font = FONT, background = "white").grid(row=1, column=0, columnspan=3, pady = 10)
    ttk.Label(self, text="Questions: ", background="white").grid(row=2, column=0,columnspan=2, padx=10, pady = 10, sticky="W")

    #Questions
    global qt
    qt = [tk.StringVar(self) for i in range(len(Questionlist_a))]
    for r in range(len(Questionlist_a)): 
        ttk.Label(self, text=Questionlist_a[r], background = "white").grid(row= r+3, column=0, columnspan=2, padx=10, pady = 10, sticky="W")
        ttk.OptionMenu(self, qt[r], *choices_y_n).grid(row = r+3, column=2, padx=10, sticky="WE")
        r=+1

    #Buttons  
    ttk.Button(self, text="Save values", command = self.save_values, width=18).grid(row=16, column=0, padx=10, pady=15, sticky="W")
    ttk.Button(self, text="Questions 2", command = lambda: controller.show_frame(__import__('Questions2').Q2),width=18).grid(row=17, column=0, padx=10, pady=15, sticky="W")

    # List of answers
    self.list_answers=[]

def save_values(self):
    self.list_answers = list(map(lambda x: x.get(), qt))

完整的回溯错误是:

Traceback (most recent call last):
File "<ipython-input-3-69ca257aaadd>", line 1, in <module>
runfile('C:/Users/nlcaste9/Desktop/New folder/Main.py', wdir='C:/Users/nlcaste9/Desktop/New folder')

File "\WPy-3662\python-3.6.6.amd64\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 668, in runfile
execfile(filename, namespace)

File "C:\Users\nlcaste9\Downloads\WPy-3662\python-3.6.6.amd64\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/nlcaste9/Desktop/New folder/Main.py", line 49, in <module>
app = HAS()

File "C:/Users/nlcaste9/Desktop/New folder/Main.py", line 33, in __init__
frame = F(container, self)

File "C:\Users\nlcaste9\Desktop\New folder\Questions1.py", line 25, in __init__
ttk.Label(self, image=Logo, background="white").grid(row=0, column=0, padx=100, columnspan=3, pady=10, sticky="W")

File "C:\Users\nlcaste9\Downloads\WPy-3662\python-3.6.6.amd64\lib\tkinter\ttk.py", line 761, in __init__
Widget.__init__(self, master, "ttk::label", kw)

File "C:\Users\nlcaste9\Downloads\WPy-3662\python-3.6.6.amd64\lib\tkinter\ttk.py", line 559, in __init__
tkinter.Widget.__init__(self, master, widgetname, kw=kw)

File "C:\Users\nlcaste9\Downloads\WPy-3662\python-3.6.6.amd64\lib\tkinter\__init__.py", line 2296, in __init__
(widgetName, self._w) + extra + self._options(cnf))

TclError: image "brand_logo.png" doesn't exist

有人可以帮助我吗?

谢谢!

标签: pythonimagetkinter

解决方案


我实际上无法重现该错误,您的代码只是没有为我显示任何图像,但我确实看到您的代码存在两个问题。

PhotoImage方法__init__定义为

class PhotoImage(Image):
    """Widget which can display colored images in GIF, PPM/PGM format."""
    def __init__(self, name=None, cnf={}, master=None, **kw):
        """Create an image with NAME.

        Valid resource names: data, format, file, gamma, height, palette,
        width."""
        Image.__init__(self, 'photo', name, cnf, master, **kw)

这意味着第一个参数是name。因此,当您调用 时Logo = tk.PhotoImage("brand_logo.png"),您会创建一个名为 的图像brand_logo.png,但实际上并未指定应使用哪个图像文件。要指定图像文件,请使用file关键字参数:

Logo = tk.PhotoImage(file="brand_logo.png")

顺便说一句,Logo仍然是__init__函数的局部变量,所以在返回之后,Logo将被垃圾收集。为了防止这种情况,通过将其重命名为任何地方使其成为实例变量self.Logo


推荐阅读