以下是我的编码,每当我点击按钮"显示平均标记"它给了我一个错误
"Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Mohammed\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args) File "C:\Users\Mohammed\Downloads\homework5_201599618.py", line 67, in showAverage
for s in self.studentList: AttributeError: 'student' object has no attribute 'studentList'
这是我的代码:
from tkinter import *
from tkinter import ttk
class student :
name = ''
number = 0
homework = 0
average = 0
def __init__(self, master):
self.master = master
master.title("student markList")
studentList = []
self.label_1 = Label(master, text = "Add student name:")
self.label_2 = Label(master, text = "Add student number:")
self.label_3 = Label(master, text = "Add homework mark:")
self.label_4 = Label(master, textvariable=self.average)
self.label_1.grid(column=1, row=1, sticky = (W,E))
self.label_2.grid(column=1, row=2, sticky = (W,E))
self.label_3.grid(column=1, row=3, sticky = (W,E))
self.label_4.grid(columnspan=3, row=8, sticky = (N,W,E,S))
self.name = StringVar()
self.number = StringVar()
self.homework = StringVar()
self.average = StringVar()
self.name_input = ttk.Entry(master, textvariable=self.name).grid(column=2, row=1, sticky = (W,E))
self.number_input = ttk.Entry(master, textvariable=self.number).grid(column=2, row=2, sticky = (W,E))
self.homework_input = ttk.Entry(master, textvariable=self.homework).grid(column=2, row=3, sticky = (W,E))
self.button_1 = Button(master, text = "Add Student Information", command=self.addStudent)
self.button_2 = Button(master, text = "List All Students", command=self.listAll)
self.button_3 = Button(master, text = "Show Average Mark", command=self.showAverage)
self.button_1.grid(column=2, row=4, sticky = (W,E))
self.button_2.grid(column=2, row=5, sticky = (W,E))
self.button_3.grid(column=2, row=6, sticky = (W,E))
self.lb1 = Listbox(master)
self.lb1.grid(columnspan=3,row=7, sticky = (W,E))
def addStudent(self, *args):
self.n = self.name.get()
self.num = self.number.get()
self.hw = self.homework.get()
self.studentList.append([self.n, self.num, self.hw])
def listAll(self):
self.lb1.delete(0, END)
for s in self.studentList:
self.lb1.insert(END,s[0] + " " + s[1] + " = " + s[2])
def showAverage(self):
self.total = 0
for s in self.studentList:
self.total += int(s[2])
self.average.set(int(self.total/len(self.studentList)))
root = Tk()
gui_markList = student(root)
root.mainloop()
我认为问题出在def(showAverage)编码中。 有人可以帮忙吗?
答案 0 :(得分:1)
在__init__
方法中,您需要将studentList = []
更改为self.studentList = []
答案 1 :(得分:1)
当你这样做时:
self.studentList.append([self.n, self.num, self.hw])
之前必须定义/赋值studentList。
在您的代码中,您所做的是:
def __init__(self, master):
self.master = master
master.title("student markList")
studentList = []
因此未将studentList分配给self /对象,因此未定义self.studentList。
您可以将其修改为:
def __init__(self, master):
self.master = master
master.title("student markList")
self.studentList = []