Why does only one button appear when creating them inside a class?

Question:

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()
Asked By: Potato Maker

||

Answers:

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.

Answered By: Bryan Oakley
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.