Search code examples
pythoncustomtkinter

Why in customtkinter I can't create 2 apps with a background


I I wanted to make 2 applications in 2 files so that I could run the second one from 1 application. But there is a problem: if a background image is placed in 1 application, then not work in 2. How can this be fixed? Here is an example of the code, the background is placed in the first and second window, work in first, but not work in the second.

import customtkinter as ctk
from PIL import Image

def start():
    App2()

class App1:
    icon1 = Image.open('res\\font33543543.jpg')
    font1 = ctk.CTkImage(icon1, size=(600, 400))

    def __init__(self):
        self.window1 = ctk.CTk()
        ctk.CTkLabel(self.window1, text='', image=self.font1).place(x=0, y=0)
        ctk.CTkButton(self.window1, command=start).place(x=10, y=10)
        self.window1.mainloop()

class App2:
    icon2 = Image.open('res\\font33543543.jpg')
    font2 = ctk.CTkImage(icon2, size=(600, 400))

    def __init__(self):
        self.window = ctk.CTk()
        ctk.CTkLabel(self.window, text='', image=self.font2).place(x=0, y=0)
        self.window.mainloop()

if __name__ == "__main__":
    App1()

When creating the second window, an error occurred:

_tkinter.TclError: image "pyimage2" doesn't exist


Solution

  • The problem is that you have 2 main windows in your app.

    You can fix it by using a CTkToplevel in the second window:

    import customtkinter as ctk
    from PIL import Image
    
    def start():
        App2()
    
    class App1:
        icon1 = Image.open('res\\font33543543.jpg')
        font1 = ctk.CTkImage(icon1, size=(600, 400))
    
        def __init__(self):
            self.window1 = ctk.CTk()
            ctk.CTkLabel(self.window1, text='', image=self.font1).place(x=0, y=0)
            ctk.CTkButton(self.window1, command=start).place(x=10, y=10)
            self.window1.mainloop()
    
    class App2:
        icon2 = Image.open('res\\font33543543.jpg')
        font2 = ctk.CTkImage(icon2, size=(600, 400))
    
        def __init__(self):
            self.window = ctk.CTkToplevel()
            ctk.CTkLabel(self.window, text='', image=self.font2).place(x=0, y=0)
    
    if __name__ == "__main__":
        App1()