首页 > 解决方案 > 运行此 GUI 时出现 PYTHON 属性错误

问题描述

所以,我正在关注制作一个简单计算器的教程,我得到一个属性错误AttributeError:'_tkinter.tkapp' object has no attribute 'displayframe',显然,源代码中甚至不存在该属性如果它已被定义?如果有人帮助将不胜感激

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()```

标签: pythonuser-interfacetkinter

解决方案


这个错误是因为你在调用self.create_display_labels()之前调用self.create_display_frame()。你也打电话self.create_digits_buttons()之前打电话self.create_buttons_frame()

移动self.create_display_labels()self.create_digits_buttons()低于self.create_display_frame()self.create_buttons_frame()。这是__init__()应该的样子:

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

推荐阅读