I have a class that contains a single button and its constructor packs it onto the root window. Why does only one button get packed onto the window when multiple objects of this class are created? Shouldn't every object have its own button?
import tkinter as tk
root = tk.Tk()
root.geometry("500x500")
class My_button:
button = tk.Button(root, width=10, height=5)
def __init__(self):
self.button.pack()
button1 = My_button()
button2 = My_button()
button3 = My_button()
root.mainloop()
CodePudding user response:
You've defined button
outside of __init__
so it is a class variable. That means it is shared by every instance of the class.
If you want each instance to have its own button, either inherit from tk.Button
so that it is a button widget, or create the instance inside of __init__
.
For more information see Class and Instance Variables in the official Python documentation.