python - tk 窗口不加载
问题描述
我目前正在为我的项目开发一个 tk 窗口 python 程序,但是 tk 窗口不会加载,并且 IDLE 中没有错误消息。请帮忙 !谢谢!
我试过在showdata和label之间切换位置,但是好像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()
对于退出按钮部分:
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
我的输出 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_
解决方案
更新:
在评论中查看它之后,您无法启动程序的问题似乎是您的方法中的while
循环showData
。
这是您的代码的重写版本。现在应该开始认为我认为您在显示数据方面可能还有其他一些问题需要解决。我还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%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()
推荐阅读
- java - InvalidArgumentException:无效参数:用户数据目录已在使用中,
- node.js - 节点没有通过 Homebrew 下载,终端卡在这行代码上,没有更新
- bash - 如何开始在 git bash 中使用 make
- python - 自定义 __del__ 不存在?
- java - 您将如何根据 Java 中的坐标检测文本?
- sql - 使用增量值指定排名值
- java - Java 线程安全性分析编译时
- javascript - 如何仅使用 context.save/context.restore、if 语句、画布和动画制作井字游戏?
- javascript - JS:从多个输入的值创建逗号分隔值
- laravel - 尝试获取单个数据并显示在 vue 组件中,但没有显示任何内容