Reputation: 11
So when I create a window and add an image it works. But then I create a window inside a function and it shows image "pyimage2" doesn't exist
. I tried adding the image as a global variable but that doesn't work either (Read on another post that it's a possible fix).
Without global variable:
import tkinter as tk
import os
os.chdir("C:/Users/flare/Desktop/moi/folders/some_files/soundbar program/")
main=tk.Tk()
background=tk.PhotoImage(file="resources/dark_grey_bg.png")
background_label=tk.Label(main,image=background)
background_label.place(x=0,y=0)
def another():
anotherwindow=tk.Tk()
bg=tk.PhotoImage(file="resources/light_grey_bg.png")
bg_label=tk.Label(anotherwindow,image=bg)
bg_label.place(x=0,y=0)
anotherwindow.mainloop()
another()
main.mainloop()
With global variable:
import tkinter as tk
import os
global bg
os.chdir("C:/Users/flare/Desktop/moi/folders/some_files/soundbar program/")
main=tk.Tk()
background=tk.PhotoImage(file="resources/dark_grey_bg.png")
background_label=tk.Label(main,image=background)
background_label.place(x=0,y=0)
def another():
global bg
anotherwindow=tk.Tk()
bg=tk.PhotoImage(file="resources/light_grey_bg.png")
bg_label=tk.Label(anotherwindow,image=bg)
bg_label.place(x=0,y=0)
anotherwindow.mainloop()
another()
main.mainloop()
Upvotes: 1
Views: 552
Reputation: 855
Posted here: Why photoimages don't exist?
"The second class I defined was the problem cause it used another root window, alias Tk(). An equivalent to the normal Tk() window is the Toplevel() that is the same as a root but hasn't its own interpreter context."
Change the second window to TopLevel()
.
import tkinter as tk
import os
os.chdir("C:/Users/flare/Desktop/moi/folders/some_files/soundbar program/")
main=tk.Tk()
background=tk.PhotoImage(file="resources/dark_grey_bg.png")
background_label=tk.Label(main,image=background)
background_label.place(x=0,y=0)
def another():
anotherwindow=tk.Toplevel()
bg=tk.PhotoImage(file="resources/light_grey_bg.png")
bg_label=tk.Label(anotherwindow,image=bg)
bg_label.place(x=0,y=0)
anotherwindow.mainloop()
another()
main.mainloop()
Upvotes: 1