tk窗口未加载

时间:2018-10-18 15:39:51

标签: python tkinter

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

我试图在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()

对于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()

学生课堂部分:

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:

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_

1 个答案:

答案 0 :(得分:0)

更新:

在注释中对其进行遍历之后,似乎无法启动程序的问题是您的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()