TK 窗口无法加载



我目前正在为我的项目开发一个 tk 窗口 python 程序,但 tk 窗口无法加载,并且 IDLE 中没有错误消息。请帮忙!谢谢!

我尝试在 showdata 和标签之间切换位置,但似乎必须首先定义标签 b4 showdata,否则会出现错误消息。

import tkinter as tk
import tkinter.scrolledtext as tkst
from quitButton import quitButton
from Student import Student
from tkinter.constants import LEFT
class Gui:
studentDL=[]
def __init__(self, root):
self.root = root
self.root.title("Simple Grading System")
self.root.geometry('600x400')
self.editArea = tkst.ScrolledText(self.root,height=5)
self.editArea.pack(expand=1, fill="both")
self.menuChoice = tk.IntVar()
self.menuChoice.set(0)
menuItems = [('Display all grade data',1),
('Display student's overall marks',2),
('Display student's whose overall marks less than 40',3)]
for (val, item) in enumerate(menuItems):
tk.Radiobutton(self.root, 
text=item[0],
variable=self.menuChoice,
command=self.showChoice,
value=val).pack(anchor=tk.W)
self.label = tk.Label(self.root, text='')
self.label.pack(side=LEFT)
self.showData()
self.averagemark() 
self.btnQ = quitButton(self.root)


def isNumber(self, s):
try:
float(s)
return True
except ValueError:
return False
def showChoice(self):
if self.menuChoice.get() == 0:
self.showData()
elif self.menuChoice.get() == 1:
self.showGrade()
elif self.menuChoice.get() == 2:
self.showfail()
def showGrade(self):
self.showData()
self.editArea.delete(1.0, tk.END)    
self.editArea.insert(tk.INSERT,('%-15s%-15s%10s%10s%10sn'%
('Student ID','Name','CW mark','Exam mark',
'Overall')))
self.editArea.insert(tk.INSERT,'='*60+'n')
for e in sorted(Gui.studentDL, key = lambda c: c.getname()):
self.editArea.insert(tk.INSERT,e) 
self.editArea.insert(tk.INSERT,'%10.2f'%e.overall()) 
self.editArea.insert(tk.INSERT,'n') 
def showData(self):
try:
fileIn = open('markdata.dat', 'r')
Gui.studentDL=[]
Student.numStudent = 0
line = fileIn.readline()
self.editArea.delete(1.0, tk.END)    
self.editArea.insert(tk.INSERT,('%-15s%-20s%15s%15sn'%('Student ID',
'Name',
'CW mark',
'Exam mark')))
self.editArea.insert(tk.INSERT,'='*60+'n')
while line != '':
Student.numStudent += 1
studentRec=line.split('_')
if len(studentRec) < 4:
self.label['text']= 'Missing data : '+line+'n'
elif studentRec[0] == '' or studentRec[1] == '':
self.label['text']= 'Invalid Student ID or Name : '+line+'n'
elif not self.isNumber(float(studentRec[2])):
self.label['text']= 'Coursework marks are not numbers : '+line+'n'  
elif not self.isNumber(float(studentRec[3])):
self.label['text']= 'Exam marks are not numbers : '+line+'n'
elif float(studentRec[2]) < 0 or float(studentRec[2]) > 100 :
self.label['text']= 'Invalid Coursework marks : '+line+'n'
elif float(studentRec[3]) < 0 or float(studentRec[3]) > 100 :
self.label['text']= 'Invalid Exam marks : '+line+'n' 
elif len(Gui.studentDL) == 0:
self.label['text']= 'empty or invalid data only : '+line+'n'

else:
Gui.studentDL.append(Student(int(studentRec[0]),
studentRec[1],
float(studentRec[2]),
float(studentRec[3])))
self.editArea.insert(tk.INSERT,('%-10s%-20s%15.2f%15.2fn'%(studentRec[0],
studentRec[1],
float(studentRec[2]),
float(studentRec[3]))))

fileIn.close()
except FileNotFoundError as error:
self.label['text']= 'File is not found! Please Rectify.'
def showfail(self):
self.showData()

overall = 0

self.editArea.delete(1.0, tk.END)
self.editArea.insert(tk.INSERT,('%-15s%-15s%10s%10s%10sn'%
('Student ID','Name','CW mark','Exam ',
'Overall')))
self.editArea.insert(tk.INSERT,'='*60+'n')
for e in sorted(Gui.studentDL, key = lambda c: c.getname()):
overall=e.overall()
if overall<40:
self.editArea.insert(tk.INSERT,e) 
self.editArea.insert(tk.INSERT,'%10.2f'%e.overall()) 
self.editArea.insert(tk.INSERT,'n')

def averagemark(self):
self.showData()
total = 0
overall = 0
for e in sorted(Gui.studentDL, key = lambda c: c.getname()):
overall += e.overall()
total += 1
average= overall/total
self.label['text']= 'Average mark is :%10.2f'%average

def main():
root = tk.Tk()
Gui(root)
root.mainloop()

if __name__ == '__main__':
main()

对于退出按钮部分:

import tkinter as tk
class quitButton(tk.Button):
def __init__(self, parent):
tk.Button.__init__(self, parent)
self['text'] = 'Quit'
self['command'] = parent.destroy
self.pack(side=tk.BOTTOM)
def main():
root = tk.Tk()
quitButton(root)
root.mainloop()
if __name__ == '__main__':
main()

学生类部分:

class Student(object):
numStudent = 0 # class variable to record number of student
CWweight = 0.4
EXweight = 0.6

def __init__(self,studID,name,coursework,exam ):
'''
constructor method
Parameters:
- studID: student ID
- name: name of student
- coursework: coursework mark
- exam: exam mark
'''
Student.numStudent += 1
self.__studID = studID
self.__name = name
self.__coursework = coursework
self.__exam = exam
def overall(self):
'''
calculate overall grade of student
'''
return self.getcoursework()*Student.CWweight + 
self.getexam()*Student.EXweight
def __str__(self):
'''
String representation of student object
'''
return '%-15d%-15s%10.2f%10.2f'%
(self.getstudID(),self.getname(),self.getcoursework(),self.getexam())
def getstudID(self):
return self.__studID
def getname(self):
return self.__name
def getcoursework(self):
return self.__coursework
def getexam(self):
return self.__exam

我的输出 标记数据.dat:

50123456_lam tai man_70.0_60.0_
50223456_li tai man_60.0_90.5_
50323456_wong tai man_34.5_30.0_
50423456_ng tai man_90.5_70.0_
50523456_lau tai man_86.0_92.4_
50623456_chui tai man_70.0_64.5_
50723456_lim tai man_64.5_60.0_
50823456_pok tai man_37.5_35.50_
50923456_kim tai man_92.4_60.0_
50023456_tsang tai man_15.0_20.0_
50999999_chan peter_100.00_80.00_

更新:

在评论中查看后,看起来您无法启动程序的问题是您showData方法中的while循环。

下面是代码的重写版本。它应该从现在开始,我认为您可能还有其他一些问题需要解决显示数据。我还studentDL作为类属性移动到类中,以便可以在内部使用它。你把Gui.studentDL叫做self.studentDL之类的东西,我会说在这里使用它作为类属性更好。

import tkinter as tk
import tkinter.scrolledtext as tkst
#from quitButton import quitButton
#from Student import Student
from tkinter.constants import LEFT

class quitButton(tk.Button):
def __init__(self, parent):
tk.Button.__init__(self, parent)
self['text'] = 'Quit'
self['command'] = parent.destroy
self.pack(side=tk.BOTTOM)

class Student(object):
numStudent = 0 # class variable to record number of student
CWweight = 0.4
EXweight = 0.6    
def __init__(self, studID, name, coursework, exam):
Student.numStudent += 1
self.__studID = studID
self.__name = name
self.__coursework = coursework
self.__exam = exam
def overall(self):
return self.getcoursework() * Student.CWweight + self.getexam() * Student.EXweight
def __str__(self):
return '%-15d%-15s%10.2f%10.2f'%(self.getstudID(), self.getname(), self.getcoursework(), self.getexam())
def getstudID(self):
return self.__studID
def getname(self):
return self.__name
def getcoursework(self):
return self.__coursework
def getexam(self):
return self.__exam

class Gui:
def __init__(self, root):
self.root = root
self.studentDL = []
self.root.title("Simple Grading System")
self.root.geometry('600x400')
self.editArea = tkst.ScrolledText(self.root, height=5)
self.editArea.pack(expand=1, fill="both")
self.menuChoice = tk.IntVar()
self.menuChoice.set(0)
menuItems = [('Display all grade data', 1), ('Display student's overall marks', 2), ('Display student's whose overall marks less than 40', 3)]
for (val, item) in enumerate(menuItems):
tk.Radiobutton(self.root, text=item[0], variable=self.menuChoice, command=self.showChoice, value=val).pack(anchor=tk.W)
self.label = tk.Label(self.root, text='')
self.label.pack(side=LEFT)
self.showData()
self.averagemark()
self.btnQ = quitButton(self.root)
def isNumber(self, s):
try:
float(s)
return True
except ValueError:
return False
def showChoice(self):
if self.menuChoice.get() == 0:
self.showData()
elif self.menuChoice.get() == 1:
self.showGrade()
elif self.menuChoice.get() == 2:
self.showfail()
def showGrade(self):
self.showData()
self.editArea.delete(1.0, tk.END)    
self.editArea.insert(tk.INSERT, ('%-15s%-15s%10s%10s%10sn' % ('Student ID', 'Name', 'CW mark', 'Exam mark', 'Overall')))
self.editArea.insert(tk.INSERT, '=' * 60 + 'n')
for e in sorted(self.studentDL, key = lambda c: c.getname()):
self.editArea.insert(tk.INSERT, e) 
self.editArea.insert(tk.INSERT, '%10.2f' % e.overall()) 
self.editArea.insert(tk.INSERT, 'n') 
def showData(self):
try:
with open('markdata.dat', 'r') as fileIn:
self.studentDL = []
Student.numStudent = 0
self.editArea.delete(1.0, tk.END)    
self.editArea.insert(tk.INSERT, ('%-15s%-20s%15s%15sn' % ('Student ID', 'Name', 'CW mark', 'Exam mark')))
self.editArea.insert(tk.INSERT, '=' * 60 + 'n')
for line in fileIn:
Student.numStudent += 1
studentRec=line.split('_')
if len(studentRec) < 4:
self.label['text'] = 'Missing data : ' + line + 'n'
elif studentRec[0] == '' or studentRec[1] == '':
self.label['text'] = 'Invalid Student ID or Name : ' + line + 'n'
elif not self.isNumber(float(studentRec[2])):
self.label['text'] = 'Coursework marks are not numbers : ' + line + 'n'  
elif not self.isNumber(float(studentRec[3])):
self.label['text'] = 'Exam marks are not numbers : ' + line + 'n'
elif float(studentRec[2]) < 0 or float(studentRec[2]) > 100 :
self.label['text'] = 'Invalid Coursework marks : ' + line + 'n'
elif float(studentRec[3]) < 0 or float(studentRec[3]) > 100 :
self.label['text'] = 'Invalid Exam marks : ' + line + 'n' 
elif len(self.studentDL) == 0:
self.label['text'] = 'empty or invalid data only : ' + line + 'n'

else:
self.studentDL.append(Student(int(studentRec[0]), studentRec[1],
float(studentRec[2]), float(studentRec[3])))
self.editArea.insert(tk.INSERT, ('%-10s%-20s%15.2f%15.2fn' % (studentRec[0], studentRec[1],
float(studentRec[2]), float(studentRec[3]))))
except FileNotFoundError as error:
print("Failed to open markdata")
self.label['text'] = 'File is not found! Please Rectify.'
def showfail(self):
self.showData()
overall = 0
self.editArea.delete(1.0, tk.END)
self.editArea.insert(tk.INSERT, ('%-15s%-15s%10s%10s%10sn' % ('Student ID', 'Name', 'CW mark', 'Exam ', 'Overall')))
self.editArea.insert(tk.INSERT, '=' * 60 + 'n')
for e in sorted(self.studentDL, key = lambda c: c.getname()):
overall = e.overall()
if overall<40:
self.editArea.insert(tk.INSERT, e)
self.editArea.insert(tk.INSERT, '%10.2f' % e.overall())
self.editArea.insert(tk.INSERT, 'n')
def averagemark(self):
self.showData()
total = 0
overall = 0
for e in sorted(self.studentDL, key = lambda c: c.getname()):
overall += e.overall()
total += 1
# added if statement to deal with dividing by zero
if overall != 0 or total != 0:
average = overall / total
else:
average = 0
self.label['text'] = 'Average mark is :%10.2f' % average

if __name__ == '__main__':
root = tk.Tk()
my_gui = Gui(root)
root.mainloop()

最新更新