[英]tk window doesn't load
I'm currently working on a tk window python program for my project, but the tk window won't load and there is no error message in IDLE. 我目前正在为我的项目开发tk窗口python程序,但是tk窗口无法加载,并且在IDLE中没有错误消息。 Please help !
请帮忙 ! Thanks!
谢谢!
I've tried to switch position between showdata and label, but it seems like the label must be defined first b4 showdata, otherwise there will be error messages. 我试图在showdata和label之间切换位置,但是似乎必须首先定义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%10s\n'%
('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%15s\n'%('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.2f\n'%(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%10s\n'%
('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()
for the quitbutton part: 对于quitbutton部分:
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()
student class part: 学生班部分:
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
my output markdata.dat: 我的输出 markdata.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_
Update: 更新:
After going over it in the comments it looks like your issue for not being able to start the program is your while
loop in your showData
method. 在注释中对其进行遍历之后,似乎无法启动程序的问题是
showData
方法中的while
循环。
Here is a rewritten version of your code. 这是代码的重写版本。 It should start now thought I think you may have some other issues to work out with displaying data.
现在应该开始,以为我认为您可能还需要解决其他一些显示数据的问题。 I also moved
studentDL
into the class as a class attribute so it can be worked with internally. 我也将
studentDL
作为类属性移到了类中,因此可以在内部使用它。 You were calling Gui.studentDL
instead something like self.studentDL
and I would say using it as a class attribute is better here. 您调用的是
Gui.studentDL
而不是诸如self.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%10s\n' % ('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%15s\n' % ('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.2f\n' % (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%10s\n' % ('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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.