python - 运行此 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()```
解决方案
这个错误是因为你在调用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
推荐阅读
- jekyll - 在 Jekyll 中设置一个没有路径的全局永久链接?
- c# - 将基类映射到集合的特定实现
- python - 使用 pandas 读取 .txt 文件并根据一列中的某个范围对其进行切片
- android - 是否可以在主要活动中从其他片段导航 navhost 片段?
- python - 将字符串作为python代码执行并存储输出+错误
- c - C - 如何将字符串数组的一部分复制到另一个?
- php - 基于不同列名的array_merge
- mysql - MySQL:某些类别的独特产品计数
- pyspark - PySpark 中的 GCS 连接器未读取 CSV
- kivy - 如何在 Kivy 中重新创建此日期滚动条?