0

The code is such that when I click on the button with an image on it. The second button must be added onto the window. But when I click on the button the second button doesn't have the same image on it.

(main.py)

from tkinter import *
import second

def main():
    root = Tk()
    first(root)

# first UI
class first:
    def __init__(self, root):
        self.root = root
        self.root.title("Demo UI")
        self.root.geometry("500x500")

        # sample button
        photo = PhotoImage(file="rot13.png")
        btn = Button(root, image=photo, command=self.switch)
        btn.pack()

        self.root.mainloop()

    def switch(self):
        second.newUI(self.root)
        return None

    pass

# run the program
main()

(second.py)

from tkinter import *

class newUI:
    def __init__(self, root):
        self.root = root

        # sample button
        photo = PhotoImage(file="rot13.png")
        btn = Button(root, image=photo)
        btn.pack()

    pass

RESULT: [1]: https://i.stack.imgur.com/3HFL1.png

x blade
  • 120
  • 10

2 Answers2

0

Check this. The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class. So I basically referenced everything so you call call the widget anywhere in the class.

from tkinter import *
import fff

def main():
    root = Tk()
    first(root)

# first UI
class first:
    def __init__(self, root):
        self.root = root
        self.root.title("Demo UI")
        self.root.geometry("500x500")

        # sample button
        self.photo = PhotoImage(file="rot13.png") #=== create a reference of the image
        self.btn = Button(self.root, image=self.photo, command=self.switch)
        self.btn.pack()

        self.root.mainloop()

    def switch(self):
        fff.newUI(self.root,self.photo) #=== Added photo parameter 
        

    pass

# run the program
main()

fff.py. The icon parameter is the path of the image

from tkinter import *
from PIL import ImageTk

class newUI:
    def __init__(self, master,icon,*args):
        self.icon = icon #=== Image Path added from the main file
        self.root = master

        # ===sample button
        
        self.btn = Button(master, image=self.icon) #== Image
        self.btn.pack()

0

You need to store a reference to photo somewhere it won't get garbage collected.

After newUI.__init__ finishes executing, photo gets garbage collected, so btn no longer has a reference to it so it doesn't appear. This is a really common mistake.

Change the following in second.py:

photo = PhotoImage(file="rot13.png")
btn = Button(root, image=photo)
btn.image = photo # so a referrence stays here, safe from the gc
btn.pack()