how to call amount in the method how to call amount in the method tkinter tkinter

how to call amount in the method


You have to bind amount to self, i.e.

amount = StringVar()

should be

self.amount = StringVar()

Accordingly, you also have to change my_entry = Entry(frm_upper, textvariable=amount) to my_entry = Entry(frm_upper, textvariable=self.amount)

Otherwise, self.amount is not defined when you do bill = float(self.amount.get()) in calculate_10_perc.


Also, note that doing

total_result = Label(...).grid(row=2, column=1)

total_result is not the Label but the result of grid, i.e. None

It seems like you are (trying to) create a new label each time you update the total value. Instead, you should configure the existing label to hold the new value. in __init__:

self.total_label = Label(frm_mid, text="")self.total_label.pack()

And in calculate_10_perc:

self.total_label.configure(text="Total after tip added: %.2f" % total)

Finally, given that all those calculate_X_perc functions will probably look very similar, you could make it one function and pass the percent as a parameter, e.g. in __init__:

btn_10_perc = Button(frm_lower, text = "10%", command=lambda: self.calculate_perc(1.1))

And the function:

def calculate_perc(self, percent):    bill = float(self.amount.get())    self.total_label.configure(text="Total after tip added: %.2f" % (bill * percent))


Ok, so the issue here is that you're not making amount an instance variable in __init__:

class TipCalc:    def __init__(self):        my_window = Tk() # create a window        my_window.title("Tip Calculator")        my_window.geometry('400x200')        amount = StringVar()        ...

Notice that you're simply declaring amount, not self.amount. This means that amount is a normal variable in __init__ that disappears when __init__ finishes, not an instance variable that lives as long as the instance exists.

Then you're getting your error here:

def calculate_10_perc(self):    bill = float(self.amount.get())

Because self.amount isn't a thing at this point - amount disappeared when __init__ finished.

So probably the easiest solution is to simply change __init__ and make amount an instance variable:

class TipCalc:    def __init__(self):        my_window = Tk() # create a window        my_window.title("Tip Calculator")        my_window.geometry('400x200')        self.amount = StringVar()        ...

Then, be sure to replace all the references to amount with self.amount.