Trying to add an image that functions like a button, but this error, image “pyimage2” doesn't exist, pops up

吃可爱长大的小学妹 提交于 2019-12-01 11:22:41

When you get an error message "_tkinter.TclError: image "pyimage2" doesn't exist" or something like that then it means tkinter can't decide which window's photo it is. This is due to of more than one Tk() windows. There are few other things that create problems when you use more than one Tk, that is why Tkinter have another type of window Toplevel and it refers to the main window like a child window.

Lets get to your code..

Here I see few other problems other than just that error.

  1. Like I said not more than one Tk() window. I believe you probably have more than two.

  2. If you have a main window and decide to open few more with Toplevel then please don't use another mainloop() one is sufficient to open as many Toplevel windows but remember to use at least one mainloop() at the end of your code.

  3. Sometimes when you define a Photoimage in a function which stored an image in a local variable the image is cleared by python even if it’s being displayed by the Label or Canvas. So always create a reference in that case.

As your code is not runnable so I added necessary things to run and test it.

from tkinter import *
from tkinter import ttk

Main_window = Tk()  # Make only one Tk main window 
Main_window.geometry('300x150')
Main_window.title("Get Shirts (Buy 1 get 1 Free)")

def small():
    s = Toplevel()   # For secondary window use Toplevel 
    s.title('Small Preset Shirt (Not fit to scale)')
    canvas = Canvas(s, width = 800, height = 100)
    canvas.pack()
    b1=ttk.Button(s,text='Click to Start', command = None)
    b1.pack()
    photo = PhotoImage(file = 'logo.png')
    b1.img_ref = photo      # Create a reference 
    b1.config(image=photo,compound=RIGHT)
    # s.mainloop()      # Don't use mainloop more than once


def stripes():
    stripes = Toplevel()  # For secondary window use Toplevel 
    stripes.title('Black Shirt with Stripes')
    canvas = Canvas(stripes, width = 800, height = 100)
    canvas.pack()
    b2=ttk.Button(stripes,text='Click to See Final Price', command = None)
    b2.pack()
    photo = PhotoImage(file = 'logo.png')
    b2.img_ref = photo      # Sometimes images in functions becomes garbage value.
    b2.config(image=photo,compound=RIGHT)
    # stripes.mainloop()      # Using two of these will do nothnig.


Category_Lb = Label(Main_window, text='Category', font=('',25))
Category_Lb.pack()

Cate_1 = ttk.Button(Main_window, text='Small Preset Shirt', command=small)
Cate_1.pack()

Cate_2 = ttk.Button(Main_window, text='Black Shirt with Stripes', command=stripes)
Cate_2.pack()


Main_window.mainloop()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!