How does my Calculator Class work in python

Viewed 84

So I have been trying to write my old code using classes and methods now and here is my query. I was recreating my calculator using tkinter and created a class that would create buttons for me (from 0 to 9). input_text is the text area where text is inserted after pressing buttons

class IsButton:
    def __init__(self, text, x, y):
        self.text = text
        self.x = x
        self.y = y

    def set_new_input(self):
        input_text.insert('end', self.text)

    def create_button(self, width=5, height=3, master=root, bg="White", fg="Black"):
        Button(master, text=self.text, height=height, width=width,
               command=self.set_new_input, bg=bg, fg=fg).place(x=self.x, y=self.y)

So I created an object i.e button1 as follows :

bt1 = IsButton("1", 20, 80)
bt1.create_button()

I understand that bt1 is created through create_button()method but how are buttons referencing what text to update on input_field when every button is created through one method.

1 Answers

If I understand what you are asking, you want to know how the button knows what text to insert into input_text. When you create an instance of IsButton, you give the text as a parameter, which is then used to set the value of self.text which is then used to insert into the text box.
A more common approach to using classes in tkinter is to subclass a widget, like button:

class NumberButton(tk.Button):
    def __init__(self, master, text, **kwargs):
        tk.Button.__init__(self, master, text = text, command = self.set_new_input, **kwargs)
        self.text = text
    def set_new_input(self):
        input_text.insert("end", self.text)

You can then use this in your code with

bt1 = NumberButton(root, "1")
bt1.place(x=20, y = 80)
Related