So, I'm following a tutorial on making a simple calculator, and I'm Getting an attribute error AttributeError:'_tkinter.tkapp' object has no attribute 'displayframe' , apparently, the attribute doesn't exist in the source code even if it has been defined? would be grateful if someone helped
from tkinter import *
SMALL_FONT_STYLE = "Arial 16"
LIGHT_GRAY = "#F5F5F5"
LABEL_COLOR = "#25265E"
LARGE_FONT_STYLE = "Arial 40 bold"
WHITE = "#FFFFFF"
class Calculator(Tk):
def __init__(self):
super().__init__()
self.geometry("375x677")
self.resizable(0,0)
self.title("Calculator")
self.total_expression = "0"
self.current_expression = "0"
self.total_label, self.label = self.create_display_labels()
self.digits = {7:(1,1), 8:(1,2), 9:(1,3), 4:(2,1), 5:(2,2), 6:(2,3), 1:(3,1),2:(3,2), 3:(3,3), 0:(4,2), '.':(4,1)}
self.create_digits_buttons()
self.display_frame = self.create_display_frame()
self.buttons_frame = self.create_buttons_frame()
def create_display_labels(self):
total_label = Label(self.display_frame, text=self.total_expression, anchor=E, bg=LIGHT_GRAY, fg=LABEL_COLOR, padx=24, font=SMALL_FONT_STYLE)
total_label.pack(expand=True, fill="both")
label = Label(self.display_frame, text=self.total_expression, anchor=E, bg=LIGHT_GRAY, fg=LABEL_COLOR, padx=24, font=LARGE_FONT_STYLE)
label.pack(expand=True, fill="both")
return total_label, label
def create_display_frame(self):
frame = Frame(self, height=221, bg=LIGHT_GRAY)
frame.pack(expand=True, fill="both")
return frame
def create_buttons_frame(self):
frame = Frame(self)
frame.pack(expand=TRUE, fill="both")
return frame
def create_digits_buttons(self):
for digit, grid_value in self.digits.items():
button = Button(self.buttons_frame, text= str(digit), bg=WHITE, fg=LABEL_COLOR)
button.grid(row = grid_value[0], column = grid_value[1], sticky=NSEW)
if __name__ == '__main__':
Calc = Calculator()
Calc.mainloop()```
CodePudding user response:
This error is because you call self.create_display_labels()
before calling self.create_display_frame()
. You also call self.create_digits_buttons()
before calling self.create_buttons_frame()
.
Move self.create_display_labels()
and self.create_digits_buttons()
below self.create_display_frame()
and self.create_buttons_frame()
. Here is what __init__()
should look like:
def __init__(self):
super().__init__()
self.geometry("375x677")
self.resizable(0,0)
self.title("Calculator")
self.total_expression = "0"
self.current_expression = "0"
self.digits = {7:(1,1), 8:(1,2), 9:(1,3), 4:(2,1), 5:(2,2), 6:(2,3), 1:(3,1),2:(3,2), 3:(3,3), 0:(4,2), '.':(4,1)}
self.display_frame = self.create_display_frame()
self.buttons_frame = self.create_buttons_frame()
self.create_digits_buttons() ### MOVED THIS LINE
self.total_label, self.label = self.create_display_labels() ### MOVED THIS LINE