我正在尝试编写一个程序来计算一个班级的成绩。我的结构方式是,用户可以添加考试,项目,实验室或其他内容,并且每个都有一定的权重。目前,我只是试图使其仅在考试中起作用。问题是我的最终成绩停留在0,因为它将最终成绩记录为默认值零。如何使其记录新值,或者甚至更好,是否有办法仅在tkinter中获取特定列的值?
def ShowFinalGrade(self):
Label(self, text= "Final Grade").grid(row=10, column=0, columnspan=3)
Label(self, text= self.Calculate()).grid(row=10, column=4)
finalpercent=87
fp = finalpercent
grading_scale = self.CreateGradeScale()
self.class_score = Button(self, text="Calculate Grade", command=self.Calculate)
self.class_score.grid(row=10, column=5, padx=50)
if fp>= grading_scale[0]:
self.finalgrade= "A"
elif fp>= grading_scale[1]:
self.finalgrade= "A-"
elif fp>= grading_scale[2]:
self.finalgrade= "B+"
elif fp>= grading_scale[3]:
self.finalgrade= "B"
elif fp>= grading_scale[4]:
self.finalgrade= "B-"
elif fp>= grading_scale[5]:
self.finalgrade= "C+"
elif fp>= grading_scale[6]:
self.finalgrade= "C"
elif fp>= grading_scale[7]:
self.finalgrade= "C-"
elif fp>= grading_scale[8]:
self.finalgrade= "D+"
elif fp>= grading_scale[9]:
self.finalgrade= "D"
else:
self.finalgrade= "F"
Label(self, text = self.finalgrade).grid(row=10, column=3, columnspan=3)
def AddExam(self):
examnumber = self.examnumber
examname = Entry(self)
examname.grid(row=examnumber+1, column=0)
examname.insert(0, "Exam "+str(examnumber))
examgrade = Entry(self)
examgrade.grid(row=examnumber+1, column=1)
examgrade.insert(0,0)
# self.examtotal += float(examgrade.get())
self.examscores.append(float(examgrade.get()))
print(examgrade) # Troubleshooting
self.examnumber+=1
def Calculate(self):
examsum = 0
if len(self.examscores)!=0:
for i in range(len(self.examscores)):
examsum+= self.examscores[i]
examavg = examsum / len(self.examscores)
else:
examavg = 0
return examavg
答案 0 :(得分:1)
当您将标签设置为text = self.Calculate()时,Python仅在该点执行Calculate函数并将其返回的结果用作标签文本。
如果您希望tkinter在每次执行新计算时自动更新标签,那么最干净的方法是使用StringVar:
self.examAverage = tk.StringVar()
Label(self, textvariable=self.examAverage).grid(row=10, column=4)
,然后在“计算”中代替
return examavg
做
self.eaxmAverage.set(examavg)
我还可以提出一种将标记fp映射到成绩的更Python化的方法-您的方法虽然有效,但未使用Python习惯用法。例如,您可以尝试:
def getGrade(self, fp):
#example grading scale
gradeBoundaries = [(95, 'A'), (85, 'A-'), (75, 'B+'),
(65, 'B'), (60, 'B-'), (55, 'C+'),
(50, 'C'), (45, 'C-'), (40, 'D+'),
(35, 'D'), (0, 'F')]
return next((grade for mark,grade in gradeBoundaries if fp>=mark),'Error')
或者,如果您希望将评分等级与成绩分开(因为每次考试的评分可能会有所不同),则可以尝试:
def getGrade(self, fp, grading_scale):
grades = 'A A- B+ B B- C+ C C- D+ D F'.split(' ')
return next((grade for mark, grade in zip(grading_scale, grades) if fp >= mark), 'Error')
,然后以实例变量或自变量的形式提供评分等级:
getGrade(70,[95,85,75,65,60,55,50,45,40,35,0])