LAM Image Annotator Homework Solutions

From PkalTides Wiki
Jump to: navigation, search

--Thiebaut (talk) 17:22, 27 July 2015 (EDT)



Back to the Liberal Arts Module page

Solution Program for Problem #1


# tkHwProblem1Sol.py
# D. Thiebaut
# 
# This program creates a TK application with 3 buttons, a label, and a text area.
# One of the buttons opens a dialog that allows the user to pick a text file.  Upon
# opening the text file, the application displays its contents in the text area, erasing
# whatever was in the area before.
# Upon clicking on the "Process" button, the application filters the text in the text-area
# and picks up all the email addresses, and displays them in the text area, in sorted order,
# and with all duplicates removed.
# 
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
 
class GUI:
    def __init__( self, rootWindow ):
        self.label = ttk.Label( rootWindow, text="-" )
        self.label.grid( row=0, column=0 )
 
        self.button1 = ttk.Button( rootWindow, text="clear",
                                   command=self.clear )
        self.button1.grid( row=0, column=1 )
 
        self.button2 = ttk.Button( rootWindow, text="Process",
                                   command=self.process )
        self.button2.grid( row=0, column=2 )
 
        self.button3 = ttk.Button( rootWindow, text="Open File",
                                   command=self.getFileName )
        self.button3.grid( row=0, column=3 )
 
        # create an object to keep the value of the checkbox
        self.buttonsEnabled = IntVar()
        self.buttonsEnabled.set( 1 )
 
        # create a checkbox and associate it with the object above.
        #self.check1 = ttk.Checkbutton( rootWindow, text="Enable", variable=self.buttonsEnabled )
        #self.check1.grid( row=0, column=3 )
 
        self.text = Text( rootWindow, width=80, height=30, background="ivory" )
        self.text.grid( row=1, column=0, columnspan=4 )
 
    def process( self ):
        if self.buttonsEnabled.get()==0:
            return
        text = self.text.get(1.0, END)
        emails = []
        # get the email addresses
        for word in text.split(  ):
            if word.find( '@' ) != -1:
                emails.append( word.strip() )
 
        # display the raw list in the text area
        self.clear()
        self.text.insert( INSERT, "\n".join( emails ) )
 
        # sort and remove duplicates
        emails = list( set( emails ) )
        emails.sort()
 
        # display the sorted list without duplicates
        self.clear()
        self.text.insert( INSERT, "\n".join( emails ) )
 
    def clear( self ):
        if self.buttonsEnabled.get()==1:
             self.text.delete(1.0, END)
        # self.buttonsEnabled.set( 1-self.buttonsEnabled.get() )
 
    def getFileName( self ):
          # get the name of a file from the user, presenting her a dialog
          fileName = filedialog.askopenfilename(filetypes = (("Text files", "*.txt"),
                                                         ("All files", "*.*")))
 
          # display name of file picked by user on the console
          #print( fileName )
          try:
              text = open( fileName, "r" ).read()
              self.clear()
              self.text.insert( INSERT, text )
              self.label.config( text = fileName.split( "/" )[-1] )
          except:
              self.label.config( text = '-' )
              pass
 
 
def main():
    global label
    rootWindow = Tk()
 
    gui = GUI( rootWindow )
    rootWindow.mainloop()
 
 
main()



Solution Program for Problem 2


# TkHomeworkSol2.py
# D. Thiebaut
# 
# This program creates a TK application with 3 buttons, a label, and two text areas.
# One of the buttons opens a dialog that allows the user to pick a text file.  Upon
# opening the text file, the application displays its contents in the left text area, erasing
# whatever was in the area before.
# Upon clicking on the "Process" button, the application filters the text in the left text-area
# and picks up all the email addresses, and displays them in the right text area, in sorted order,
# and with all duplicates removed.
# 
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
 
class GUI:
    """This class holds all the widgets of the GUI, including the actions attached to the
    different buttons"""
 
    def __init__( self, rootWindow ):
        """The constructor.  Creates the widgets and positions them on the GUI"""
        self.label = ttk.Label( rootWindow, text="-" )
        self.label.grid( row=0, column=0 )
 
        self.button1 = ttk.Button( rootWindow, text="clear",
                                   command=self.clear )
        self.button1.grid( row=0, column=1 )
 
        self.button2 = ttk.Button( rootWindow, text="Process",
                                   command=self.process )
        self.button2.grid( row=0, column=2 )
 
        self.button3 = ttk.Button( rootWindow, text="Open File",
                                   command=self.getFileName )
        self.button3.grid( row=0, column=3 )
 
        # create an object to keep the value of the checkbox
        self.buttonsEnabled = IntVar()
        self.buttonsEnabled.set( 1 )
 
        # create the 2 text-areas, side by side        
        self.text1 = Text( rootWindow, width=40, height=30, background="ivory" )
        self.text1.grid( row=1, column=0, columnspan=2 )
        self.text2 = Text( rootWindow, width=40, height=30, background="ivory" )
        self.text2.grid( row=1, column=2, columnspan=2 )
 
    def process( self ):
        """this method is attached to the Process button.  Takes the contents of
        the left text-area, splits it into words, and each word containing a @-sign
        is kept and added to a list.  The list is eventually sorted, duplicates removed,
        and displayed in the second text-area."""
 
        # get the text from the left text-area
        text = self.text1.get(1.0, END)
        emails = []
 
        # extract the email addresses
        for word in text.split(  ):
            if word.find( '@' ) != -1:
                emails.append( word.strip() )
 
        # sort and remove duplicates
        emails = list( set( emails ) )
        emails.sort()
 
        # display the sorted list without duplicates in the right text-area
        self.clear2()
        self.text2.insert( INSERT, "\n".join( emails ) )
 
    def clear( self ):
        """ clear both text-areas"""
        self.clear1()
        self.clear2()
        # reset file name to a dash
        self.label.config( text = '-' )
 
    def clear1( self ):
        """clears the left text-area """
        self.text1.delete(1.0, END)
 
    def clear2( self ):
        """clears the right text-area """
        self.text2.delete(1.0, END)
 
    def getFileName( self ):
          """ get the name of a file from the user, presenting her a dialog.  The text of the
          file is automatically added to the left text-area."""
 
          fileName = filedialog.askopenfilename(filetypes = (("Text files", "*.txt"),
                                                         ("All files", "*.*")))
 
          # display name of file picked by user on the console
          #print( fileName )
          try:
              text = open( fileName, "r" ).read()
              self.clear1()
              self.text1.insert( INSERT, text )
              self.label.config( text = fileName.split( "/" )[-1] )
          except:
              self.label.config( text = '-' )
              pass
 
 
def main():
    global label
    rootWindow = Tk()
 
    gui = GUI( rootWindow )
    rootWindow.mainloop()
 
 
main()