Dear Community! No matter how I try to write the code, one image always appears twice! What’s wrong?
import tkinter as tk
from tkinter import ttk
class Szulo(ttk.Frame):
def __init__(self, container):
super().__init__(container)
self.kep1 = tk.PhotoImage(file='../globalkep/z11.png')
ttk.Button(self, image=self.kep1).pack(padx=5, pady=5)
class Gyerek(Szulo):
def __init__(self, container):
super().__init__(container)
self.kep2 = tk.PhotoImage(file='../globalkep/p11.png')
ttk.Button(self, image=self.kep2).pack(padx=5, pady=5)
class App(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('600x500+500+50')
self.configure(bg='green')
szulo = Szulo(self)
szulo.pack(padx=20, pady=20)
gyerek = Gyerek(self)
gyerek.pack(padx=20, pady=20)
if __name__ == '__main__':
app = App()
app.mainloop()
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Heya,
The issue you’re facing is because the
Gyerek
class inherits from theSzulo
class and, during initialization, it callssuper().__init__(container)
. This means that when you create an instance ofGyerek
, both theSzulo
andGyerek
initialization code will be run, resulting in two images being created and displayed: the image from the parent class (kep1
) and the one from the child class (kep2
).Since the child (
Gyerek
) class is designed to inherit from the parent (Szulo
), it will always run theSzulo
initialization, which packs the button with thekep1
image. Then theGyerek
class adds its own image (kep2
), leading to both images being shown.If you want only one image in the child class (
Gyerek
), you’ll need to modify the design a bitYou could move the button creation for
kep1
into a separate method and call it only when needed: