I’m currently working on my portfolio in Python Tkinter. While I tried to make buttons simpler and add an icon to my windows, I saw this bug occuring, where it says "image ‘pyimage17 or 18 or 19, etc.’ does not exist.". To make buttons look better, I used this button factory website, where I can make buttons to my liking. All I had to do is just don’t add any texts, fonts, instead just disable the border (border=0), and add the button style as the background image. I used this "technique" inside every window of mine. I use different python files to store other button functionalities, so the problem may be because I’m using the same image too much. Here’s the thing though. When I removed the icon, the problem was still appearing, and I don’t use the same button image anywhere else.
There might be a solution, which is just remove all buttons and go with the boring default button style, but I don’t want my portfolio app to be boring.
Also, if I open the file which has a function imported to another file, the window appears just fine and how I planned it to appear. But if I run the main file (menu), then the problem occurs. E. g.
from tkinter import *
def buttonFunc1():
root = Tk()
root.geometry("800x500")
imageInstance = PhotoImage(file="path/to/image/file")
button = Button(root, image=imageInstance, border=0)
button.pack()
root.mainloop()
if __name__ == '__main__':
buttonFunc1()
If I run the code, it appears just fine. If I import it to another file like this and run it:
from tkinter import *
from file_example1 import buttonFunc1
menu = Tk()
imageInstance2 = PhotoImage(file="path/to/another/image/file")
menu.geometry('800x500')
button_to_another_window = Button(menu, image=imageInstance2, border=0, command=buttonFunc1)
button_to_another_window.pack()
menu.mainloop()
the error I mentioned earlier appears if I click the button. Please tell me an easy fix.
I know, my description is a bit wordy, but please read it.
I tried using Image and ImageTk from the PIL module, no luck. I tried to ask ChatGPT, it didn’t help. I tried asking multiple AI’s from character.ai, no luck.
>Solution :
Each time you create a window with Tk() you are creating a new, isoloated environment. Any image you create in one window will not be available in some other window.
Tkinter automatically generates internal names for images by incrementing a counter. So, the first image in a window is pyimage1, then pyimage2, etc. If you get an error about pyimage17, that means you’ve created at least 17 images in one window. If you try to use this in a second window created by Tk(), it will fail since the image only exists in the first window.
As a general rule of thumb you should never create more than one instance of Tk. If you need multiple windows in a single app, use Toplevel() for the second and subsequent window since they will exist in the same isolated environment as the root window.