Deleting objects in Python 1.6

Alex cut_me_out at hotmail.com
Wed May 3 17:21:48 CEST 2000


> it segfaults on my machine, unless I use a v. new Python

Ah, I see.  Thanks.

Alex.

From: Cindy Huyser <chuyser at flash.net>
Newsgroups: comp.lang.python
Subject: Re: Trouble with Pmw ComboBox get()
Date: Tue, 02 May 2000 23:18:50 -0500
Organization: Computer Science, Southwest Texas State Univ.
Lines: 1817
Message-ID: <390FA8A9.DF091DA2 at flash.net>
References: <390D7ACA.5CB91267 at flash.net>
NNTP-Posting-Host: p182-31.atnt3.dialup.aus2.flash.net
Mime-Version: 1.0
Content-Type: multipart/mixed;
 boundary="------------983E28FFC622C20F3CC7A2B0"
X-Trace: comets.cs.swt.edu 957327242 19873 216.215.31.182 (3 May 2000 04:14:02 GMT)
X-Complaints-To: gripe at cs.swt.edu
NNTP-Posting-Date: 3 May 2000 04:14:02 GMT
X-Mailer: Mozilla 4.61 [en] (Win95; I)
X-Accept-Language: en
Path: news!uunet!ffx.uu.net!newsfeed.nyc.globix.net!news.new-york.net!cpk-news-hub1.bbnplanet.com!news.gtei.net!cs.utexas.edu!news.swt.edu!news.cs.swt.edu!not-for-mail
Xref: news comp.lang.python:93529
To: python-list at python.org
Sender: python-list-admin at python.org
Errors-To: python-list-admin at python.org
X-BeenThere: python-list at python.org
X-Mailman-Version: 2.0beta3
Precedence: bulk
List-Id: General discussion list for the Python programming language <python-list.python.org>

This is a multi-part message in MIME format.
--------------983E28FFC622C20F3CC7A2B0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit


More complete information on the Pmw ComboBox get() problem:

I've attached the primary files for this program. Run main.py, and
choose Available Rooms from the View menu to get the course scheduler
overview.  Here, attempting to add or delete a course scheduled doesn't
have the desired effect --this is where the problem shows up -- the
default values are always loaded into the code.

Something else that's weird is the set of labels that's showing up at
the bottom of the page -- I don't think I wrote code that put them
there!

I retyped this file from an earlier version that was working pretty well
(but didn't do file reads).  In this version, I've hard coded in all the
information I had been reading from files.  The substantial difference
between this version and the one in which the course addition/deletion
is working is the way in which information is communicated between the
file handler functions in main() and the data structures in schedule.py
and roomGrid.py, and I imagine this is where the trouble lies.
--------------983E28FFC622C20F3CC7A2B0
Content-Type: text/plain; charset=us-ascii;
 name="listAll.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="listAll.py"

from Tkinter import *
import pickle


class listAll:

   def __init__(self, courseDict, courseList, parent):
      self.courseList = courseList
      self.courseDict = courseDict

      
      self.listFrame=Frame(parent, height=435, width=730)
      self.listFrame.pack()
      self.listPage=Text(self.listFrame, height=435, width=730)
      self.listScroll=Scrollbar(self.listFrame, command=self.listPage.yview)
      self.listPage.configure(yscrollcommand=self.listScroll.set)

      self.processCourses(self.courseList, self.courseDict)

      self.listPage.pack(side=LEFT)
      self.listScroll.pack(side=RIGHT, fill=Y)
     


########## Function to parse course list ##########

   def processCourses(self, courseList, courseDict):

      self.listPage.tag_configure('CourseName', font=("Arial", 10, "bold"))
      self.listPage.tag_configure('Title', font=("Arial", 12, "bold"))

      self.listPage.insert(END, "\t\t\t\t\t LIST OF ALL SCHEDULED COURSES\n\n\n", 'Title')

      courseNums=[]

      courseList.sort()

      for key in courseDict.keys():
         courseNums.append(key)

      courseNums.sort()

      printed=0

      for num in courseNums:
         printed=0
         for course in courseList:
            if course[0]==num:
               if printed==0:
                  self.listPage.insert(END, '\n\n\t\t\t\t' + num + ' -- ' + courseDict[num] + '\n\n', 'CourseName')
                  printed=1
               if printed==1:
                  self.formatAndPrintCourse(course)


########## Function to transform course listing into string ##########

   def formatAndPrintCourse(self, course):

      self.listPage.tag_configure('usual', font=("Arial", 10))
      self.listPage.tag_configure('conflict', foreground="red", font=("Arial", 10))


      if course[6]==1:
         courseText = course[0] + "  " + course[1] + "  " + course[2] +"  " +  course[3] + "  " +  course[4] + "  " + course[5] +"  " + "Lab"
                                       
      else:
         courseText = course[0] +  "  " +course[1] + "  " +course[2] +  "  " +course[3] + "  " +course[4] + "  " +course[5]

      self.listPage.insert(END,'\t\t\t\t\t'+ courseText+'\n', 'usual')


########## Function to redraw course list ###########

   def redraw(self, schedule):

      self.courseList=schedule
      self.listPage.delete(1.0,END)
      self.processCourses(self.courseList, self.courseDict)
      self.listPage.pack(side=LEFT)



########## END LISTALL FUNCTIONS ###########


if __name__ == '__main__':

   # Read the course numbers
   f = open('courses.txt', 'r')
   words = pickle.load(f)
   f.close()
   courseDict=words

# Read the course list

   f = open('sched0.chd', 'r')
   if f:
      words=pickle.load(f)
      f.close()
      courseList=words

   root = Tk()
   root.title("List All Scheduled Courses")
   theList=listAll(courseDict, courseList, root)
   root.mainloop()


--------------983E28FFC622C20F3CC7A2B0
Content-Type: text/plain; charset=us-ascii;
 name="main.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="main.py"

from Tkinter import *
from tkFileDialog import *
from editDay import *
from editBeginTime import *
from editTimeBlock import *
from editInstructor import *
from editCourse import *
from editRoom import *
import listAll
import schedule




class AllMenus:
    def __init__(self, parent):
        self.parent = parent
        self.menubar = Menu(parent)
        self.opened = 0
        self.roomsLoaded=0
        
        ## create the File pulldown menu
        self.filemenu=Menu(self.menubar, tearoff=0)
        self.filemenu.add_command(label = "New", command=self.newFile)
        self.filemenu.add_command(label = "Open", command=self.openFile)
        self.filemenu.add_command(label = "Close", command=self.closeFile)
        self.filemenu.add_separator()
        self.filemenu.add_command(label = "Save", command=self.saveFile)
        self.filemenu.add_command(label = "Save As", command=self.saveFileAs)
        self.filemenu.add_separator()
        self.filemenu.add_command(label = "Page Setup")
        self.filemenu.add_command(label = "Print")
        self.filemenu.add_separator()
        self.filemenu.add_command(label = "Import")
        self.filemenu.add_command(label = "Export")
        self.filemenu.add_separator()
        self.filemenu.add_command(label = "Exit", command = parent.destroy)
        
        self.menubar.add_cascade(label = "File  ", menu=self.filemenu)

        ## create the Edit pulldown menu
        self.editmenu=Menu(self.menubar, tearoff=0)
        self.editmenu.add_command(label = "Courses", command = self.course)
        self.editmenu.add_command(label = "Instructors", command = self.classInstructor)
        self.editmenu.add_command(label = "Class Rooms", command = self.classRoom)
        self.editmenu.add_separator()
        self.editmenu.add_command(label = "Class Days", command = self.classDay)
        self.editmenu.add_command(label = "Class Begin Times", command = self.classBeginTime)
        self.editmenu.add_command(label = "Class Time Blocks", command = self.classTimeBlock)
        self.editmenu.add_separator()
        self.editmenu.add_command(label = "Class Tags")
        
        self.menubar.add_cascade(label = "Edit  ", menu=self.editmenu)
        self.ofile=None
        self.currName=None
        
        
        ## create the View pulldown menu
        self.viewmenu=Menu(self.menubar, tearoff=0)
        self.viewmenu.add_command(label = "By Courses", command=self.loadCourses)
        self.viewmenu.add_command(label = "By Instructors", command=self.loadFaculty)
        self.viewmenu.add_command(label = "By Class Tags", command=self.loadTags)
        self.viewmenu.add_separator()
        self.viewmenu.add_command(label = "Available Class Rooms", command=self.loadRooms)
        self.viewmenu.add_separator()
        self.viewmenu.add_command(label = "All", command=self.loadListAll)        
        self.menubar.add_cascade(label = "View  ", menu=self.viewmenu)

        ## create the Help pulldown menu
        self.helpmenu=Menu(self.menubar, tearoff=0)
        self.helpmenu.add_command(label = "Help Topics", command = self.help)
        self.helpmenu.add_separator()
        self.helpmenu.add_command(label = "About Class Scheduling", command = self.about)
        self.menubar.add_cascade(label = "Help  ", menu=self.helpmenu)
                       
        self.parent.config(menu=self.menubar)
	
    def loadRooms(self):

        
        if self.parent.curView==allList:
           noUpdate=1

        self.parent.prevView=self.parent.curView
        self.parent.curView.forget()
        roomsAvailFrame.pack()
        if self.roomsLoaded==0:
           roomsView.drawInit(classSchedule)
           self.roomsLoaded=1
        self.parent.curView=roomsAvailFrame
        roomsTitle="Class Scheduling System -- Available Rooms"
        root.title(roomsTitle)

    def loadFaculty(self):

        self.parent.prevView=self.parent.curView
        self.parent.curView.forget()
        facultyFrame.pack()
        self.parent.curView=facultyFrame
        facultyTitle="Class Scheduling System -- By Instructor"
        root.title(facultyTitle)

    def loadCourses(self):

        self.parent.prevView=self.parent.curView
        self.parent.curView.forget()
        coursesFrame.pack()
        self.parent.curView=coursesFrame
        coursesTitle="Class Scheduling System -- By Course"
        root.title(coursesTitle)

    def loadTags(self):

        self.parent.prevView=self.parent.curView
        self.parent.curView.forget()
        tagsFrame.pack()
        self.parent.curView=tagsFrame
        tagsTitle="Class Scheduling System -- By Tags"
        root.title(tagsTitle)

    def loadListAll(self):
   
        self.parent.prevView=self.parent.curView
        self.parent.curView.forget()
        allFrame.pack()
        allList.redraw(classSchedule)
        self.parent.curView=allFrame
        allTitle="Class Scheduling System -- All Courses Scheduled"
        root.title(allTitle)


    def closeFile(self):
        if self.opened:
           while len(self.parent.classSchedule)>0:
              del self.parent.classSchedule[0]
        roomsView.eraseData()
        self.parent.curView.forget()
        emptyframe.pack()
        self.viewmenu.configure(disabledforeground)
        plainTitle="Class Scheduling System"
        root.title(plainTitle)


    def openFile(self):
        if self.opened:
           while len(self.parent.classSchedule)>0:
              del self.parent.classSchedule[0]
        self.ofile=askopenfilename(filetypes=[("Schedule", ".chd"),("Text", ".txt"), ("All files", ".*")])
        if self.ofile:
           f = open(self.ofile, 'r')
           words=pickle.load(f)
           f.close()
           self.parent.classSchedule=words[:]
           self.loadRooms()
           self.opened=1

    def newFile(self):
        if self.opened:
           while len(self.parent.classSchedule)>0:
              del self.parent.classSchedule[0]
        self.ofile=None


    def saveFile(self):
        if self.ofile:
           f=open(self.currName, 'w')
           pickle.dump(classSchedule, f)
           f.close()
        else:
           self.saveFileAs()

    def saveFileAs(self):

        self.ofile=asksaveasfilename(filetypes=[("Schedule", ".chd")])

        if self.ofile:
           self.currName=self.ofile
           fd=open(self.currName, 'w')
           pickle.dump(classSchedule, fd)
           fd.close()
        
        

    ## popup window to edit class days

    def classDay(self):
        self.tops = Toplevel(self.parent)
        self.d = ClassDay(self.tops)

    def classBeginTime(self):
        self.tops = Toplevel(self.parent)
        self.d = ClassBeginTime(self.tops)

    def classTimeBlock(self):
        self.tops = Toplevel(self.parent)
        self.d = ClassTimeBlock(self.tops)
    
    def classInstructor(self):
        self.tops = Toplevel(self.parent)
        self.d = ClassInstructor(self.tops)

    def course(self):
        self.tops = Toplevel(self.parent)
        self.d = Course(self.tops)        

    def classRoom(self):
        self.tops = Toplevel(self.parent)
        self.d = ClassRoom(self.tops)
        # Read the rooms
        f = open('crooms.txt', 'r')
        words = pickle.load(f)
        f.close()
        self.parent.allRooms=words

        # Empty the current structures
        while len(self.parent.rooms)>0:
           del self.parent.rooms[0]
        while len(self.parent.labs)>0:
           del self.parent.labs[0]

        # Refill the room structures
        for item in words.keys():
           if words[item]==0:
              self.parent.rooms.append(item)
           else:
              labs.append(item)

        roomsView.redrawRooms()


    def about(self):
        self.tops = Toplevel(self.parent)
        self.tops.title("About CSS")
        self.l = Label(self.tops, width = 80, height = 15, font=("Helvetica", 10, "bold"), text = "The Class Scheduling System (CSS)\n April, 2000\n\nDeveloped by Yue Xi, Cindy Huyser, Jayesh Patel, Wendy Chen\n\n CSS was developed as a class project for Graphical User Interface course\n in Southwest Texas State University")  
        self.b = Button(self.tops, text = "OK", width = 10, command = self.tops.destroy)
        self.l.pack()
        self.b.pack(side = BOTTOM, pady = 10)
    def help(self):
        self.tops = Toplevel(self.parent)
        self.tops.title("Help Topics on CSS")
        self.l = Label(self.tops, text = "Help Topics", width = 40, height = 10, font = ("Helvetica", 15, "bold"))
        self.b = Button(self.tops, text = "OK", width = 10, command = self.tops.destroy)
        self.l.pack()
        self.b.pack(side = BOTTOM, pady = 10)

############# READ INFORMATION FROM FILES ###########

# Read common data structures for the views

#classSchedule=[]     # List of classes scheduled
courses={}     # Dictionary of course numbers with course names
conflicts={}
#courseNums=[]  # To be read from courses
#faculty=[]
allRooms={}
#days=[]
#timeBlocks=[]
#startTimes=[]

#rooms=[]
#labs=[]

#f = open('sched0.chd', 'r')
#words=pickle.load(f)
#f.close()
#classSchedule=words

# Read the rooms
#f = open('crooms.txt', 'r')
#words = pickle.load(f)
#f.close()
#allRooms=words

#for item in words.keys():
#   if words[item]==0:
#      rooms.append(item)
#   else:
#      labs.append(item)

# Read the day combinations
#f = open('days.txt', 'r')
#words=pickle.load(f)
#f.close()
#days=words

# Read the start times
#f = open('startt~1.txt', 'r')
#words=pickle.load(f)
#f.close()
#times=words
# Convert tuple to list
#count=0
#while count<len(times):
#   startTimes.append(times[count])
#   count=count+1
    

# Read the time blocks
#f = open('ctimeb~1.txt', 'r')
#words=pickle.load(f)
#f.close()
#timeBlocks=words

# Read the course numbers
#f = open('courses.txt', 'r')
#words = pickle.load(f)
#f.close()
#courses=words

#for key in courses.keys():
#   courseNums.append(key)
#   courseNums.sort()

# Read the faculty names
#f = open('cinstr~1.txt', 'r')
#words=pickle.load(f)
#f.close()
#facultyNames=words
#faculty=[]
#count=0
#while count<len(facultyNames):
##   faculty.append(facultyNames[count])
#   count=count+1
#faculty.sort()
   # Declare the lists 

courseNums=["CS3339", "CS3358", "CS3409", "CS4310", "CS4332", "CS5346", "CS5389"]
faculty=["Ogden, Robert", "Hall, David", "Davis, Wilbon", "Hwang C. Jinshong", "McCabe, Thomas"]   
rooms=['DH113', 'DH231', 'DH241', 'DH310']
labs=["MCS325", "DH325"]  
timeBlocks=["50 min", "75 min", "175 min"]
days=["M", "T", "W", "H", "F", "MW", "TH", "MWF"]
startTimes=["8:00am", "8:30am", "9:00am", "9:30am", "10:00am", "10:30am", "11:00am",
               "12:00N", "12:30pm", "1:00pm", "1:30pm","2:00pm","2:30pm","3:00pm",
               "3:30pm","4:00pm","4:30pm","5:00pm","5:30pm","6:00pm","6:30pm","7:00pm",
               "7:30pm","8:00pm","8:30pm","9:00pm"]
classSchedule=[]

classSchedule.append(("CS3409" ,"Ogden, Robert","MWF", "8:00am", "75 min","DH113", 0))
classSchedule.append(("CS3409" ,"Ogden, Robert","MWF", "8:00am", "75 min","DH113", 0)) 



########### Initialize schedule and conflicts dictionaries ############

# On save, write common data structures
                                        
root = Tk()
title = "Class Scheduling System"
root.title(title)

############ DECLARE THE VIEWS #############
# Make the frames for the various views

# Empty view
emptyframe=Frame(root, width=770, height=435)
emptiness=Canvas(emptyframe, width=770, height=435)
emptiness.pack(side=TOP)

# Welcome screen
welcomeframe = Frame(root, width = 50, height = 10)
welcome = Label(welcomeframe, text = "Welcome To \n\nthe Class Scheduling System",width = 50, height = 16, bg = "white", fg = "blue",font = ("Helvetica", 20, "bold italic"))
root.curView=welcomeframe
root.prevView=None
welcomeframe.pack()
welcome.pack(fill = BOTH, expand = 1)

# Rooms available view
roomsAvailFrame=Frame(root, width=770, height=435)
roomsView=schedule.roomsAvail(classSchedule, courseNums, days, startTimes, timeBlocks, faculty, rooms, labs, roomsAvailFrame)

# View by faculty
facultyFrame=Frame(root, width=770, height=435)
tempFacultyLabel=Label(facultyFrame, text= "This is the view by instructor", width=500, height=300, bg="white", fg="navy",
font=("Arial", 18, "bold"))
tempFacultyLabel.pack(fill=BOTH, expand=1)

# View by courses
coursesFrame=Frame(root, width=770, height=435)
tempCoursesLabel=Label(coursesFrame, text="This is the view by courses", width=500, height=300,bg="white", fg="red", font=("Arial", 18, "bold"))
tempCoursesLabel.pack(fill=BOTH, expand=1)

# View by tags
tagsFrame=Frame(root, width=770, height=435)
tempTagsLabel=Label(tagsFrame, text="This is the view by tags", width=500, height=300,bg="white", fg="forest green", font=("Arial", 18, "bold"))
tempTagsLabel.pack(fill=BOTH, expand=1)

# List view of all courses
allFrame=Frame(root, width=770, height=435)
allList=listAll.listAll(courses, classSchedule, allFrame)

m = AllMenus(root)

mainloop()



   

--------------983E28FFC622C20F3CC7A2B0
Content-Type: text/plain; charset=us-ascii;
 name="roomGrid.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="roomGrid.py"

#/usr/local/python

# Programmer: C. Huyser
# CS5389 Spring 2000
# Group 4


from Tkinter import *


class roomGrid:
  def __init__(self, schedule, conflicts, startTimes, rooms, labRooms, courses, master):

     # Preserve attributes

     self.master=master
     self.gridCourses=schedule # Dictionary of classes 
     self.gridConflicts=conflicts    # Conflicts dictionary
     self.startTimes=startTimes

     self.rooms=[]     # To be created from rooms and colors
     self.labRooms=[]       #To be created from rooms and colors
     self.courses=courses 

     # Associate the rooms with their colors
     self.colorRooms(rooms, labRooms)

     
     ################# FRAMING FOR LAYOUT ###################

     self.frame0=Frame(master, borderwidth=0, width=770, height=310, relief=GROOVE)
     self.frame0.pack(side=TOP)
     self.frameDetails=Frame(self.frame0, borderwidth=0, width=770, height=55, relief=GROOVE)
     self.frameDetails.pack(side=TOP)
     self.frameGrid=Frame(self.frame0, borderwidth=0, width=770, height=251, relief=GROOVE)
     self.frameGrid.pack(side=TOP)

     
     ################# DETAILS AREA ################

     # Declare a flag for focus on course details
     self.detailsFocus=0

     # Flag to toggle changeability of detail area
     self.fixDetails=0
     # Variable to catch the index of a detail that's been fixed
     self.fixIndex=0

     ########### Draw the detail area for frame 1 ############

     # Declare variable for # of courses in grid cell
     self.prevLen=0

     self.buildDetails()
 

     #########################################################

     ##  FORCED VALUES FOR DETAILS SECTION (NOT WORKING) ##
      
     self.gridx=-1
     self.gridy=-1


     ########## DIVIDE THE GRID AREA ##########

     # Create the frames for the room grid area

     daysArea=Frame(self.frameGrid, borderwidth=0, width=20, height=250) # Week labels
     gridArea=Frame(self.frameGrid, borderwidth=0)  # will contain grid + time labels
     legendArea=Frame(self.frameGrid, borderwidth=0, width=94, height=250)
     daysArea.pack(side=LEFT)
     gridArea.pack(side=LEFT)
     legendArea.pack(side=LEFT)


     # Create the frames for the grid and time labels

     gridTimes=Frame(gridArea, borderwidth=0, width=676, height=15)
     theGrid=Frame(gridArea, borderwidth=2, relief=SOLID, width=676, height=236)
     gridTimes.pack(side=TOP)
     theGrid.pack(side=TOP)



     ########## MAKE THE GRID ##########

     # Use a canvas object for the grid

     self.grid=Canvas(theGrid, width=672, height=236, bg="white")
     self.grid.bind("<Motion>",self.tracking)
     self.grid.bind("<Button-1>", self.toggleDetails)
     self.drawGrid()


     # Use a canvas for the hours labels

     self.gridHours=Canvas(gridTimes, width=672, height=20)
     self.drawHours()


 
     # Use a canvas for the day labels   

     self.weekLbl=Canvas(daysArea, width=14, height=300)
     self.drawDays()


  
     # Use another canvas object for the room legend color marks

     self.legend=Canvas(legendArea, width=80, height=300)

     # Make the "LEGEND" label, then draw the legend

     self.legend.create_text(42, 50, text="LEGEND", font=("arial", 10, "bold"))
     self.drawLegend(self.rooms, self.labRooms)



     ########## INITIALIZATION ##########

     ####### Build dictionaries to hold room, conflict, and coordinate info ########

     self.gridRooms={}
     self.gridLabs={}
     self.gridCoords={}

     # Declare variables for course processing
     self.courseToAdd=[]
     self.courseToRemove=[]
     self.courseIndices=[]



     # Initialize the dictionaries

     self.initializeRooms(self.rooms, self.labRooms)
    
     # Process the classes passed in from the parent
     self.processCourses(self.courses)
   
     # Declare variables for time block size and index into grid

     self.blockSize=0
     self.gridIndex=-1

     self.currentX=-1
     self.currentY=-1

############################# VALUES FORCED FOR TESTING #######################

          


###############################################################################

     # Draw the initialized view


     self.drawRooms(self.gridRooms, self.gridLabs, self.gridConflicts)



######################## FUNCTIONS FOR THE ROOMGRID CLASS #####################

########### Function to toggle changeability of details ##########

  def toggleDetails(self, event):

     if self.fixDetails==0:
        self.fixDetails=1
     else:
        self.fixDetails=0


########## Function to clear the room and conflicts dictionaries ############

  def clearRooms(self):
     for item in range(140):
        while len(self.gridRooms[item])>0:
           del self.gridRooms[item][0]
        while len(self.gridLabs[item])>0:
           del self.gridLabs[item][0]
        while len(self.gridConflicts[item])>0:
           del self.gridConflicts[item][0]


########## Function to build details area ##########

  def buildDetails(self):
   
     # Start with a canvas item
     self.details=Canvas(self.frameDetails, borderwidth=0, width=790, height=90)
     self.details.pack()


     # Insert a frame for the class details and draw it

     self.viewChoiceFrame=Frame(self.details, width=335, height=70)
     self.viewChoiceFrame.pack(side=LEFT)
     self.detailsView=Text(self.details, width=300, height=40)
     self.detailsScroll=Scrollbar(self.details, command=self.detailsView.yview)
     self.detailSpace=Canvas(self.details, width=150, height=55)
     self.detailsLabelFrame=Frame(self.details, width=300, height=15)
     self.detailsLabel=Label(self.detailsLabelFrame, text="Schedule Details", font=("Arial", 10, "bold"))
     self.detailsExplain=Label(self.detailsLabelFrame, text="( *** denotes conflict )", font=("Arial", 9))
     self.detailSpace.pack(side=RIGHT)
     self.detailsLabelFrame.pack(side=TOP)
     self.detailsLabel.pack(side=LEFT)
     self.detailsExplain.pack(side=RIGHT)
     self.detailsScroll.pack(side=RIGHT, fill=Y)
     self.detailsView.pack(side=RIGHT)


     # Draw a series of labels in the frame, to be used for detail info
     self.detail0=Label(self.detailsView, text="", width=250, bg="white", font=("Arial", 8), takefocus=1)
     self.detail1=Label(self.detailsView, text="", width=250, bg="white", font=("Arial", 8), takefocus=1)
     self.detail2=Label(self.detailsView, text="", width=250, bg="white", font=("Arial", 8), takefocus=1)
     self.detail3=Label(self.detailsView, text="", width=250, bg="white", font=("Arial", 8), takefocus=1)
     self.detail4=Label(self.detailsView, text="", width=250, bg="white", font=("Arial", 8), takefocus=1)
     self.detail5=Label(self.detailsView, text="", width=250, bg="white", font=("Arial", 8), takefocus=1)

     self.detailsView.window_create(END, window=self.detail0)
     self.detailsView.window_create(END, window=self.detail1)
     self.detailsView.window_create(END, window=self.detail2)
     self.detailsView.window_create(END, window=self.detail3)
     self.detailsView.window_create(END, window=self.detail4)
     self.detailsView.window_create(END, window=self.detail5)



     self.detailLabelList=[self.detail0, self.detail1, self.detail2, self.detail3, self.detail4,
                           self.detail5]

     # Pack the labels
     self.detail0.pack(side=TOP)
     self.detail1.pack(side=TOP)
     self.detail2.pack(side=TOP)
     self.detail3.pack(side=TOP)
     self.detail4.pack(side=TOP)
     self.detail5.pack(side=TOP)

########## Function to track position of mouse in grid ##########

  def tracking(self, event):

     # Calculate index into course dictionary
     self.gridx=event.x
     self.gridy=event.y
     index=self.getIndex(self.gridx, self.gridy)

     if not self.fixDetails:

        # Fill the labels
        if len(self.gridCourses[index])==0:
           if self.prevLen==0:
              pass
           else:
              for label in self.detailLabelList:
                 label.configure(text="")
                 label.pack()
        else:
           # Empty out previous labels
           if self.prevLen==0:
              pass
           else:
              for label in self.detailLabelList:
                 label.configure(text="")
                 label.pack()
           # Draw current labels.
           count=0
           for course in self.gridCourses[index]:
              if course[6]==1:
                 courseText = course[0] + "  " + course[1] + "  " + course[2] +"  " +  course[3] + "  " +  course[4] + "  " + course[5] +"  " + "Lab"
                                       
              else:
                 courseText = course[0] +  "  " +course[1] + "  " +course[2] +  "  " +course[3] + "  " +course[4] + "  " +course[5]
              if course[5] in self.gridConflicts[index]>0:
                 courseText = "*** " + courseText
              self.detailLabelList[count].configure(text=courseText, font=("Arial", 8))
              self.detailLabelList[count].pack()
              count=count+1

           # Keep track of how many courses presented in previous calculation
           self.prevLen=len(self.gridCourses[index])
     else:
        self.fixIndex=index

     


########## Function to compute index of item in grid from coordinates ##########

  def getIndex(self, xpos, ypos):

     return (ypos/48)*28+(xpos/24)



########## Function to associate colors with rooms ##########

  def colorRooms(self, rooms, labRooms):

     roomColors=["blue", "forest green", "orange", "plum", "yellow"]
     labColors=["black", "cyan", "gray", "purple"]

     print "Rooms: ", rooms
     print "Labs: ", labRooms

     # Start fresh
     index=len(self.rooms)-1
     while index>=0:
        del self.rooms[index]
        index=index-1

     index=len(self.labRooms)-1
     while index>=0:
        del self.labRooms[index]
        index=index-1

     # Build the tuples
     count = 0
     for room in rooms:
        self.rooms.append((rooms[count], roomColors[count]))
        count = count+1

     count=0
     for lab in labRooms:
        self.labRooms.append((labRooms[count], labColors[count]))
        count = count+1


########## Function to draw grid ##########

  def drawGrid(self):

     # Vertical first

     xpos=24
     for i in range(27):
        self.grid.create_line(xpos,0,xpos,236)
        xpos=xpos+24

     # Then horizontal

     ypos=48
     for i in range(5):
        self.grid.create_line(0,ypos,672,ypos)
        ypos=ypos+48

########## Function to draw time labels ##########


  def drawHours(self):

     # Make the time labels

     timeBegin=['8a', '9a', '10a', '11a', '12N',
                '1p', '2p', '3p', '4p', '5p',
                '6p', '7p', '8p', '9p', '10p']

     # Draw text for each of the times

     xpos=9
     ypos=14
     count=0
     for time in timeBegin:
        self.gridHours.create_text(xpos, ypos, text=time, font=("arial", 10, "bold"))
        if(count==0):
           xdiff=39
        elif (count==13):
           xdiff=40
        else:
           xdiff=48
        xpos=xpos+xdiff
        count=count+1

     # Pack the hours labels

     self.gridHours.pack()



########## Function to draw day labels ##########


  def drawDays(self):

     # Make a list of days of the week

     enumDays=['M', 'T', 'W', 'H', 'F']

     # Draw text for each of the days

     xpos=10
     ypos=70
     ydiff=48
     for day in enumDays:
        self.weekLbl.create_text(xpos, ypos, text=day, font=("arial", 10, "bold"))
        ypos=ypos+ydiff

     self.weekLbl.pack()


########## Function to draw rooms ##########

  def drawRooms(self, rooms, labs, conflicts):

     # Clear grid
     self.grid.delete(ALL)

     self.drawGrid()

     for item in range(140):
        x=self.gridCoords[item][0]
        y=self.gridCoords[item][1]
        roomCount=0

        # Draw conflicts

        if len(conflicts[item])!=0:
           self.grid.create_rectangle(x-2, y-2, x+22, y+46, fill="red")

        # Draw classrooms
        for room, color in rooms[item]:
           self.grid.create_oval(x, y, x+6, y+6, fill=color)
           roomCount=roomCount+1
           if roomCount%4!=0:
              y=y+12
           else:
              x=x+12
              y=y-36

        # Draw labs
        for room, color in labs[item]:
           self.grid.create_rectangle(x, y, x+6, y+6, fill=color)
           roomCount=roomCount+1
           if roomCount%4!=0:
              y=y+12
           else:
              x=x+12
              y=y-36

        self.grid.pack()


########## Function to draw legend ##########

  def drawLegend(self, rooms, labs):

     ypos=73
     for roomname, color in rooms:
        self.legend.create_oval(10, ypos, 18, ypos+8, fill=color)
        self.legend.create_text(50, ypos+4, text=roomname, font=("arial", 10, "bold")) 
        ypos=ypos+20

     for roomname, color in labs:
        self.legend.create_rectangle(10, ypos, 18, ypos+8, fill=color)
        self.legend.create_text(50, ypos+4, text=roomname, font=("arial", 10, "bold"))
        ypos=ypos+20

     self.legend.create_oval(10, ypos+5, 18, ypos+13)
     self.legend.create_text(52, ypos+9, text="= classroom", font=("arial", 8))
     self.legend.create_rectangle(10, ypos+25, 18, ypos+33)
     self.legend.create_text(33, ypos+29, text="= lab", font=("arial", 8))

     self.legend.pack()



########## Function to read new info ##########

  def readRoomInfo(self, rooms, labs):

     for item in range(140):
        self.gridRooms[item]=rooms[:]
        self.gridLabs[item]=labs[:]
        self.grid.pack()


########## Function to initialize grid with information ##########

  def initializeRooms(self, rooms, labs):

     xpos=2
     ypos=2
     for item in range(140):
        self.gridCoords[item]=(xpos, ypos)
        if (item+1)%28==0:
           xpos=2
           ypos=ypos+48
        else:
           xpos=xpos+24
     self.readRoomInfo(rooms, labs)


########## Function to redraw grid information ##########

  def redraw(self, changeType, course, modCourse=None):

     # Room list(s) changed
     if changeType==-1:
        self.initializeRooms(self.rooms, self.labRooms)
        self.drawRooms(self.gridRooms, self.gridLabs, self.gridConflicts)

     # Drawing grid and rooms for first time
     elif changeType==0:
        self.initializeRooms(self.rooms, self.labRooms)
        self.processCourses(course)
        self.drawRooms(self.gridRooms, self.gridLabs, self.gridConflicts)

     # Adding a class
     elif changeType==1:
        self.processCourses(course)
        self.drawRooms(self.gridRooms, self.gridLabs, self.gridConflicts)

     # Deleting a class
     elif changeType==2:
        self.delCourse(course)
        self.drawRooms(self.gridRooms, self.gridLabs, self.gridConflicts)

     # Modifying a class
     elif changeType==3:
        self.changeCourse(course, modCourse)
        self.drawRooms(self.gridRooms, self.gridLabs, self.gridConflicts)


########## Function to update room information ##########

  def updateRooms(self, rooms, labs):

     self.colorRooms(rooms, labs)
     self.legend.delete(ALL)
     self.drawLegend(self.rooms, self.labRooms)
     self.redraw(-1, self.courses)



########## Function to convert time blocks to number of half hours ##########

  def convertTimeBlock(self, timeBlock):

     # Get the index of the item just past the number
     for i in range(len(timeBlock)):
        if timeBlock[i]==' ':
           index=i

     # Slice the time block to get the number
     minutes=eval(timeBlock[0:index])

     # Calculate block size
     if minutes%30==0:
        self.blockSize=minutes/30
     else:
        self.blockSize=minutes/30 + 1


########## Function to convert day, time to grid index ##########

  def convertDayTime(self, day, time):

     # Make lists of days, times for conversion
     days=["M", "T", "W", "H", "F"]
                                           
     dayIndex=days.index(day) 
     timeIndex=self.startTimes.index(time)

     self.gridIndex=(dayIndex*28)+timeIndex


########## Function to process courses ###########

#### Builds entries in course dictionary and adjusts room dictionaries accordingly

  def processCourses(self, courses):

     print "Courses -- before process: ", courses
     for course in courses:
        self.addCourse(course)


########## Function to determine indices given course ##########

  def getIndices(self, course):

     temp=[] 

     # Empty the indices holder
     while len(self.courseIndices)>0:
        del self.courseIndices[0]

     # Compute initial indices
     for day in course[2]:
        self.convertDayTime(day, course[3])
        temp.append(self.gridIndex)

     self.convertTimeBlock(course[4])

     for block in range(self.blockSize):
        for item in temp:
           self.courseIndices.append(item+block)
          
########## Function to add course to grid dictionary ##########

  def addCourse(self, course):

     # Make a list of the indices of the items to be added
     self.getIndices(course)

     # Subtract a room from the room list

     if course[6]==0:
        # Pair the room with its color
        for room in self.rooms:
           if course[5]==room[0]:
              courseTuple=(room[0], room[1])
        for item in self.courseIndices:
           # Remove the room
           if courseTuple in self.gridRooms[item]:
              self.gridRooms[item].remove(courseTuple)

     # Subtract a room from the lab room list
     else:
        # Pair the room with its color
        for room in self.labRooms:
           if course[5]==room[0]:
              courseTuple=(room[0], room[1])

        for item in self.courseIndices:
           # Remove the room, if it exists
           if courseTuple in self.gridLabs[item]:
              self.gridLabs[item].remove(courseTuple)

########## Function to remove course from grid dictionary ##########

  def delCourse(self, course):

     # Make a list of the indices of the items to be deleted
     self.getIndices(course)

     # If not registered as conflict and not in list of courses, add back in to the room list

     for index in self.courseIndices:
        if (course[5] in self.gridConflicts[index])==0:
           if len(self.gridCourses[index])>0:
              itemCount=0
              for item in self.gridCourses[index]:
                 if (course[5] in self.gridCourses[index][itemCount])==0:
                    if course[6]==0:
                       # Pair the room with its color
                       for room in self.rooms:
                          if course[5]==room[0]:
                             courseTuple=(room[0], room[1])
                       self.gridRooms[index].append(courseTuple)
                    else:
                       # Pair the room with its color
                       for room in self.labRooms:
                          if course[5]==room[0]:
                             courseTuple=(room[0], room[1])
                       self.gridLabs[index].append(courseTuple)
              itemCount=itemCount+1
           else:
              if course[6]==0:
                 # Pair the room with its color
                 for room in self.rooms:
                    if course[5]==room[0]:
                       courseTuple=(room[0], room[1])
                 self.gridRooms[index].append(courseTuple)
              else:
                 # Pair the room with its color
                 for room in self.labRooms:
                    if course[5]==room[0]:
                       courseTuple=(room[0], room[1])
                 self.gridLabs[index].append(courseTuple)


########### Function to modify course in grid dictionary ##########

  def changeCourse(self, oldCourse, newCourse):
     pass


########## END OF FUNCTIONS #########


# if __name__=='__main__': roomGrid().mainloop()

--------------983E28FFC622C20F3CC7A2B0
Content-Type: text/plain; charset=us-ascii;
 name="schedule.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="schedule.py"

#!/usr/local/python

# Programmer: C. Huyser
# CS 5389 Spring 2000
# Group 4


from Tkinter import *

from tkMessageBox import askyesno
from tkMessageBox import showerror

import Pmw

from roomGrid import *


class roomsAvail:
  def __init__(self, schedule, courseNums, days, startTimes, timeBlocks, faculty, rooms, labs, master):

     self.master=master
     self.rooms=rooms
     self.labRooms=labs
     self.startTimes=startTimes
     self.timeBlocks=timeBlocks
     self.dayCombs=days
     self.faculty=faculty
     self.courses=courseNums
     self.schedule=schedule

     #Create the frames that outline the page shape
     self.frame1=Frame(master, borderwidth=0, width=770, height=410)
     self.frame1.pack(side=TOP)

     self.frame2=Frame(self.frame1, borderwidth=0, width=770, height = 310, relief=GROOVE)
     self.frame2.pack(side=TOP)

     self.frame3=Frame(self.frame1, borderwidth=0, width=770, height=100, relief=SOLID)
     self.frame3.pack(side=TOP)


     # Declare dictionaries for courses and conflicts
     self.classSchedule={}
     self.conflicts={}
     self.cRooms={}
     self.cLabs={}
     self.cFaculty={}
     self.cTags={}


     # Structures for selected items in combo boxes
     self.courseSel=[]
     self.roomSel=[]
     self.facultySel=[]
     self.timeSel=[]
     self.blockSel=[]
     self.daySel=[]
     self.labStatus=IntVar() 

     # Variables to hold static copies of rooms or comparison when updating
     self.roomCopy=self.rooms[:]
     self.labCopy=self.labRooms[:]


     # Single-element lists of (tuple) holding a classroom
     self.newCourse=[]
     self.oldCourse=[] 

     # Variable to hold calculated course indices    
     self.courseIndices=[]


     #########################################################


     self.allRooms=self.rooms+self.labRooms
     self.allRooms.sort()


     # Initialize the dictionaries
     self.initializeDictionaries()


     # Process courses and conflicts     
     self.readCourses()
     
     # Draw the class add/edit/delete area

     self.buildCourse()


     # Here's the room grid
     self.grid=roomGrid(self.classSchedule, self.conflicts, self.startTimes, self.rooms, self.labRooms, self.schedule, self.frame2)


##################### SUPPORTING FUNCTIONS ######################

########## Function to build course area ##########

  def buildCourse(self):

     #### STRUCTURE FOR SCHEDULE CLASS AREA ####

     self.courseRow0=Frame(self.frame3, width=770, height=15)
     self.courseCRow1=Frame(self.frame3, width=770, height=40)
     self.courseButtons=Frame(self.frame3, width=770, height=45)
     self.courseRow0.pack(side=TOP)
     self.courseCRow1.pack(side=TOP)
     self.courseButtons.pack(side=TOP)

     # Draw the labels over the combo boxes

     self.courseTitles=Canvas(self.courseRow0, width=770, height=15)
     self.courseTitles.create_text(100,10, text="Course #",font=("Arial", 10, "bold"))
     self.courseTitles.create_text(235,10, text="Instructor",font=("Arial", 10, "bold"))
     self.courseTitles.create_text(346,10, text="Day(s)",font=("Arial", 10, "bold"))
     self.courseTitles.create_text(430,10, text="Time Begin", font=("Arial", 10, "bold"))
     self.courseTitles.create_text(530,10, text="Time Block", font=("Arial", 10, "bold"))
     self.courseTitles.create_text(625,10, text="Room #", font=("Arial", 10, "bold"))
     self.courseTitles.create_text(715,10, text="Lab", font=("Arial", 10, "bold"))
     self.courseTitles.pack(side=TOP)

     #### Draw the combo boxes, check box, and buttons ####

     self.courseCombo=Pmw.ComboBox(self.courseCRow1, entry_width=8, 
                              listbox_width=10,dropdown=1,
                              scrolledlist_items=self.courses)
     self.courseCombo.pack(side=LEFT, expand=1, padx=5, pady=2)
     self.courseCombo.selectitem(self.courses[0])


     self.facultyCombo=Pmw.ComboBox(self.courseCRow1,
                              listbox_width=10,dropdown=1,
                              scrolledlist_items=self.faculty)
     self.facultyCombo.pack(side=LEFT, expand=1, padx=5, pady=2)
     self.facultyCombo.selectitem(self.faculty[0])

     self.dayCombsCombo=Pmw.ComboBox(self.courseCRow1, entry_width=6,                                                                                          listbox_width=10,dropdown=1,
                              scrolledlist_items=self.dayCombs)
     self.dayCombsCombo.pack(side=LEFT, expand=1, padx=5, pady=2)
     self.dayCombsCombo.selectitem(self.dayCombs[0])

     self.startTimeCombo=Pmw.ComboBox(self.courseCRow1, entry_width=8,                                                                                                                        listbox_width=10,dropdown=1,
                              scrolledlist_items=self.startTimes)
     self.startTimeCombo.pack(side=LEFT, expand=1, padx=5, pady=2)
     self.startTimeCombo.selectitem(self.startTimes[0])
     
     self.timeBlockCombo=Pmw.ComboBox(self.courseCRow1, entry_width=10,
                              listbox_width=10,dropdown=1,
                              scrolledlist_items=self.timeBlocks)
     self.timeBlockCombo.pack(side=LEFT, expand=1, padx=5, pady=2)
     self.timeBlockCombo.selectitem(self.timeBlocks[0])

     self.roomsCombo=Pmw.ComboBox(self.courseCRow1,entry_width=12,                                                       listbox_width=10,dropdown=1,
                              scrolledlist_items=self.allRooms)
     self.roomsCombo.pack(side=LEFT, expand=1, padx=5, pady=2)
     self.roomsCombo.selectitem(self.allRooms[0])

     self.labCheck=Checkbutton(self.courseCRow1, text="", state=NORMAL,                                variable=self.labStatus)
     self.labCheck.pack(side=LEFT)


     self.crsDelBtn=Button(self.courseButtons, text="Delete Class", padx=5, pady=3, command=self.delClass)
     self.crsEditBtn=Button(self.courseButtons,text="Edit Class", padx=9, pady=3, state=DISABLED, command=self.editClass)
     self.crsAddBtn=Button(self.courseButtons,text="Add Class", padx=9, pady=3, command=self.addClass)

     self.crsSpace1=Canvas(self.courseButtons, height=45 ,width=200)
     self.crsSpace2=Canvas(self.courseButtons, height=45, width=30)
     self.crsSpace3=Canvas(self.courseButtons, height=45, width=30)
     self.crsSpace4=Canvas(self.courseButtons, height=45, width=200)

     self.crsSpace1.pack(side=RIGHT)
     self.crsDelBtn.pack(side=RIGHT)
     self.crsSpace2.pack(side=RIGHT)
     self.crsEditBtn.pack(side=RIGHT)
     self.crsSpace3.pack(side=RIGHT)
     self.crsAddBtn.pack(side=RIGHT)
     self.crsSpace4.pack(side=RIGHT)



################ DICTIONARY MANIPULATION FUNCTIONS ##############

########## Function to empty data structures ##########

  def eraseData(self):

     for item in range(140):
        # Empty the dictionaries
        while len(self.classSchedule[item])>0:
           del self.classSchedule[item][0]
        while len(self.conflicts[item])>0:
           del self.conflicts[item][0]
        while len(self.cTags[item])>0:
           del self.cTags[item][0]
        while len(self.cFaculty[item])>0:
           del self.cFaculty[item][0]
        while len(self.cRooms[item])>0:
           del self.cRooms[item][0]
        while len(self.cLabs[item])>0:
           del self.classSchedule[item][0]


########## Function to rebuild dictionaries ##########

  def rebuildDictionaries(self):

     self.eraseData()

     # Refill the dictionaries
     self.cRooms=self.rooms[:]
     self.cLabs=self.labRooms[:]
     self.cFaculty=self.faculty[:]
     #self.cTags=self.tags[:]


########## Function to update room dictionaries ##########

  def updateRoomDictionaries(self):

     roomsToAdd=[]
     labsToAdd=[]
     roomstoRemove=[]
     labsToRemove=[]

     # Discover the difference between new and old dictionaries

     for item in roomCopy:
        if not item in self.rooms:
           roomsToRemove.append(item)

     for item in self.rooms:
        if not item in roomCop:
           roomsToAdd.append(item)

     for item in labCopoy:
        if not item in self.labRooms:
           labsToRemove.append(item)

     for item in self.labRooms:
        if not item in labCopy:
           labsToAdd.append[item]

     for item in range(140):
        for room in roomsToAdd:
           self.cRooms.append(room)
        for room in roomsToRemove:
           self.cRooms.remove(room)
        for room in labsToAdd:
           self.cLabs.append(room)
        for room in labsToRemove:
           self.cLabs.remove(room)



########## Function to initialize dictionaries ##########

  def initializeDictionaries(self):

     for item in range(140):
        self.classSchedule[item]=[]
        self.conflicts[item]=[]
        self.cTags[item]=[]
        self.cFaculty[item]=[]
        self.cRooms[item]=self.rooms[:]
        self.cLabs[item]=self.labRooms[:]
        #self.cFaculty[item]=self.faculty[:]     


################      REDRAW FUNCTIONS     ##############


########## Function to redraw course and grid areas WRT rooms ##########

  def redrawRooms(self):

     self.buildCourse()
     self.frame3.pack()
     self.updateRoomDictionaries()
     self.grid.updateRooms(self.rooms, self.labRooms)


########## Function to draw initial view ##########

  def drawInit(self, schedule):
     self.schedule=schedule
     self.initializeDictionaries()
     self.buildCourse()
     self.frame2.pack()
     self.readCourses()
     self.grid.redraw(0, self.schedule)


########## Function to redraw course and grid area ###########

  def redraw(self, schedule):

     self.schedule=schedule
     self.buildCourse()
     self.frame2.pack()
     self.rebuildDictionaries()
     self.readCourses()
     self.grid.redraw(0, self.schedule)


################     INDEX CALCULATIONS     ###############

##########  Function to calculate course indices ##########

  def getIndices(self, course):

     temp=[] 

     # Empty the indices holder
     while len(self.courseIndices)>0:
        del self.courseIndices[0]

     # Compute initial indices
     for day in course[2]:
        self.convertDayTime(day, course[3])
        temp.append(self.gridIndex)

     self.convertTimeBlock(course[4])

     for block in range(self.blockSize):
        for item in temp:
           self.courseIndices.append(item+block)

########## Function to convert time blocks to number of half hours ##########

  def convertTimeBlock(self, timeBlock):

     # Get the index of the item just past the number
     for i in range(len(timeBlock)):
        if timeBlock[i]==' ':
           index=i

     # Slice the time block to get the number
     minutes=eval(timeBlock[0:index])

     # Calculate block size
     if minutes%30==0:
        self.blockSize=minutes/30
     else:
        self.blockSize=minutes/30 + 1


########## Function to convert day, time to grid index ##########

  def convertDayTime(self, day, time):

     # Make lists of days, times for conversion
     days=["M", "T", "W", "H", "F"]

     dayIndex=days.index(day) 
     timeIndex=self.startTimes.index(time)

     self.gridIndex=(dayIndex*28)+timeIndex



################  CONFLICTS DETERMINATION   ################

########## Function to check for conflicts in class assignments ##########

  def findConflicts(self, course, indices):

     # Set a return value flag to call the yes/no conflict dialog
     found = 0

     for item in indices:
        # Check for classroom conflicts
        if course[6]==0:
           if (course[5] in self.cRooms[item])==0:
              # Already removed from list -- room scheduled more than once
              self.conflicts[item].append(course[5])
              found=1
           else:
              self.cRooms[item].remove(course[5])

        # Check for lab conflicts
        else:
           if (course[5] in self.cLabRooms[item])==0:
              # Already removed from list -- room scheduled more than once
              self.conflicts[item].append(course[5])
              found=1
           else:
              self.cLabRooms[item].remove(course[5])

     return found


########## Function to remove conflicts in class assignments ##########

  def removeConflicts(self, course, indices):

     for item in indices:

        # If no conflict, update the rooms dictionary
        if (course[5] in self.conflicts[item])==0:
           if course[6]==0:
              self.cRooms[item].append(course[5])
           else:
              self.cLabRooms[item].append(course[5])

        # Update the conflicts dictionary
        if (course[5] in self.conflicts[item])>0:
           self.conflicts[item].remove(course[5])


#################  DATA MANIPULATION  ##################


########## Function to read courses into courses and course conflicts dictionaries ##########

  def readCourses(self):

     # Make a list of the indices of the items to be added
     for course in self.schedule:
        self.getIndices(course)

        # Find conflicts and append them to conflicts dictionary
        foundConflict=self.findConflicts(course, self.courseIndices)

        # Append the course to the course dictionary
        for item in self.courseIndices:
           self.classSchedule[item].append(course)


########## Function to add a class to the schedule ##########

  def addClass(self, courseToAdd=None):

     while len(self.newCourse)>0:
        del self.newCourse[0]
 
     # Function works for passed parameter and combo box read
     if not courseToAdd:
        self.newCourse.append((self.courseCombo.get(), self.facultyCombo.get(),
                              self.dayCombsCombo.get(), self.startTimeCombo.get(),
                              self.timeBlockCombo.get(), self.roomsCombo.get(),
                              self.labStatus.get()))
     else:
        self.newCourse.append(courseToAdd)
     
     self.getIndices(self.newCourse[0])

     # Find conflicts and append them to conflicts dictionary
     foundConflict=self.findConflicts(self.newCourse[0], self.courseIndices)

     # If conflict found, prompt the user
     if foundConflict==1:
        answer=askyesno("Conflict Detected", "Adding this course will produce a conflict.  Do you want to schedule it anyway?")
        if answer==1:
           # Append the class to the list of classes
           self.schedule.append(self.newCourse[0])

           # Append the course to the course dictionary
           for item in self.courseIndices:
              self.classSchedule[item].append(self.newCourse[0])

           # Course schedule has been updated; send course to make room changes
           self.grid.redraw(1, self.newCourse)

        else:
           # Undo the change to the conflicts dictionary
           self.removeConflicts(self.newCourse[0], self.courseIndices)

     elif foundConflict==0:

        # Append the class to the list of classes
        self.schedule.append(self.newCourse[0])

        # Append the course to the course dictionary
        for item in self.courseIndices:
           self.classSchedule[item].append(self.newCourse[0])

        # Course schedule has been updated; send course to make room changes
        self.grid.redraw(1, self.newCourse)

########## Function to delete a class from the schedule ##########

  def delClass(self, courseToRemove=None):

     while len(self.oldCourse)>0:
        del self.oldCourse[0]

     # Function works for passed parameter and combo box read
     if not courseToRemove:
        self.oldCourse.append((self.courseCombo.get(), self.facultyCombo.get(),
                              self.dayCombsCombo.get(), self.startTimeCombo.get(),
                              self.timeBlockCombo.get(), self.roomsCombo.get(),
                              self.labStatus.get()))
     else:
        self.oldCourse.append(courseToRemove)

     # Trap for class not in schedule
     if not self.oldCourse[0] in self.schedule:
        errorBox=showerror("Class Not Found", "The class selected for deletion was not found in the schedule, and could not be deleted.")
        return

     self.getIndices(self.oldCourse[0])
     self.removeConflicts(self.oldCourse[0], self.courseIndices)

     # Remove the course from the course list and dictionary
     for index in self.courseIndices:
        self.classSchedule[index].remove(self.oldCourse[0])        
     self.schedule.remove(self.oldCourse[0])

     self.grid.redraw(2, self.oldCourse[0])


########## Function to edit a class in the schedule ##########

  def editClass(self, course):

     ####### THIS CODE ISN'T FUNCTIONAL ######

     if len(self.oldCourse)>0:
        del self.oldCourse[0]
     if len(self.newCourse)>0:
        del self.newCourse[0]

     # Get current course and put in oldCourse

     #self.readOldCourse(self.oldCourse[0])
     self.newCourse.append((self.courseCombo.get(), self.facultyCombo.get(),
                           self.dayCombsCombo.get(), self.startTimeCombo.get(),
                           self.timeBlockCombo.get(), self.roomsCombo.get(),
                           self.labStatus.get()))

     self.getIndices(self.newCourse[0])

     self.schedule.append(self.newCourse[0])
     self.removeConflicts(self.oldCourse[0], self.courseIndices)
     self.schedule.remove(self.oldCourse[0])

     self.grid.redraw(3, self.oldCourse, self.newCourse)

###################### END OF AVAILROOMS FUNCTIONS ####################### 

   
if __name__=='__main__':

   # Declare the lists 

   courses=["CS3339", "CS3358", "CS3409", "CS4310", "CS4332", "CS5346", "CS5389"]
   faculty=["R. Ogden", "D. Hall", "W. Davis", "C. Hwang", "T. McCabe"]   
   rooms=['DH113', 'DH231', 'DH241', 'DH310']
   labRooms=["MCS325", "DH325"]  
   timeBlocks=["50 min", "75 min", "175 min"]
   dayCombs=["M", "T", "W", "H", "F", "MW", "TH", "MWF"]
   startTimes=["8:00am", "8:30am", "9:00am", "9:30am", "10:00am", "10:30am", "11:00am",
               "12:00N", "12:30pm", "1:00pm", "1:30pm","2:00pm","2:30pm","3:00pm",
               "3:30pm","4:00pm","4:30pm","5:00pm","5:30pm","6:00pm","6:30pm","7:00pm",
               "7:30pm","8:00pm","8:30pm","9:00pm"]
   schedule=[]

   schedule.append(("CS3409" ,"Ogden, Robert","MWF", "8:00am", "75 min","DH113", 0))
   schedule.append(("CS3409" ,"Ogden, Robert","MWF", "8:00am", "75 min","DH113", 0)) 

   root=Tk()
   root.title("Course Schedule -- Rooms Available")
   display=roomsAvail(schedule, dayCombs, startTimes, timeBlocks, faculty, courses, rooms, labRooms, root)
   root.mainloop()


--------------983E28FFC622C20F3CC7A2B0--




More information about the Python-list mailing list