Contents

  1. Chapter 3.1 class average program with counter-controled repetition
  2. Chapter 3.2 Class average program with sentinel-controlled repetition
  3. Chapter 3.3 Analysis of examination results
  4. Chapter 4.1 Recursive factorial function
  5. Chapter 4.2 Recursive fibonacci function 0,1,1,2,3,5,8,13,21
  6. Chapter 5.1 Unpacking sequences
  7. Chapter 7.1 simple definition of class Time
  8. Chapter 7.2 Class Time with accessor methods
  9. Chapter 7.3 Class Time with default constructor
  10. Chapter 7.4 Class Employee with class attribute count
  11. Chapter 8.1 Representation of phone number in USA format: (xxx) xxx-xxxx
  12. Chapter 8.2 Class Time with customized attribute access
  13. Chapter 9.1 derived class inheriting from a base class
  14. Chapter 9.2 Overriding base-class methods
  15. Chapter 9.3 Creating a class hierarchy with an abstract base class
  16. Chapter 9.4 Class Employee with a static method
  17. Chapter 9.5 Class that defines method __getattribute__
  18. Chapter 9.6 simple class with slots
  19. Chapter 9.7 Class Time with properties
  20. Chapter 10.1 Label demonstration
  21. Chapter 10.2 Entry components and event binding demostration
  22. Chapter 10.3 Button demonstration
  23. Chapter 10.4 Checkbuttons demostration
  24. Chapter 10.5 Radiobuttons demonstration
  25. Chapter 10.6 Mouse events example
  26. Chapter 10.7 Binding keys to keyboard events
  27. Chapter 10.8 pack layout manager demonstration
  28. Chapter 10.9 Grid layout manager demonstration
  29. Chapter 10.10 Card shuffling and dealing program
  30. Chapter 11.1 ScrolledListBox used to select image
  31. Chapter 11.2 Copying selected text from one text area to another
  32. Chapter 11.3 MenuBars with Balloons demonstration
  33. Chapter 11.4 Popup menu demonstration
  34. Chapter 11.5 Canvas paint program
  35. Chapter 11.6 Scale used to control the size of a circle
  36. Chapter 12.1 Simple exception handling example
  37. Chapter 12.2 Demonstrating a programer-defined exception class
  38. Chapter 13.1 Searching string for a substring
  39. Chapter 13.2 Simple regular-expression example
  40. Chapter 13.3 Compiled regular-expression and match objects
  41. Chapter 13.4 Regular-expression string manipulation
  42. Chapter 13.5 Program that demonstrates grouping and greedy operations
  43. Chapter 14.1 Opening and writing to a file
  44. Chapter 14.2 Reading and printing a file
  45. Chapter 14.3 Credit inquiry program
  46. Chapter 14.4 Writing to shelve file
  47. Chapter 14.5 Reading shelve file
  48. Chapter 14.6 file operation
  49. Chapter 14.7 Opening and writing pickled object to file
  50. Chapter 14.8 Reading and printing pickled object in a file
  51. Chapter 16.1 making up a text file's data as XML
  52. Chapter 16.2 using 4DOM to traverse an XML Document
  53. Chapter 16.3 Using 4DOMto manipulate an XML Document
  54. Chapter 16.4 Demonstrating SAX-based parsing
  55. Chapter 17.1 Displays contents of the Authors table,ordered by a specified field
  56. Chapter 17.2 diaplay results returned by a query on a database
  57. Chapter 18.1 Using fork to create child processes
  58. Chapter 18.2 Demostrates the os.wait function
  59. Chapter 18.3 demostrates the waitpid function
  60. Chapter 18.4 Uses the system function to clear the screen
  61. Chapter 18.5 Opens a Web page in a system-specific editor
  62. Chapter 18.6 Demonstrating popen and popen2
  63. Chapter 18.7 Using os.pipe to communicate with a child process
  64. Chapter 18.8 Defining our own signal handler
  65. Chapter 18.9 Sending signals to child processes using kill
  66. Chapter 19.1 Multiple threads printing at different intervals
  67. Chapter 19.2 Multiple threads modifying shared object
  68. Chapter 19.3 Integer-producing class
  69. Chapter 19.4 Integer-consuming queue
  70. Chapter 19.5 Unsynchronized access to an integer
  71. Chapter 19.6 Multiple threads modifying shared object
  72. Chapter 19.7 Synchronized access to an integer with condition variable
  73. Chapter 20.1 Display the contents of a file from a Web server in a browse
  74. Chapter 20.2 server side socket program
  75. Chapter 20.3 client side socket program
  76. Chapter 20.4 receive packets from a client and send packets to a client
  77. Chapter 20.5 send packets to a server and receive packets from a server
  78. Chapter 21.1 Demostrating crypto system
  79. Chapter 22.1 Classes List and Node definitions

Chapter 3.1 class average program with counter-controled repetition

   1 #chapter 3.1
   2 #class average program with counter-controled repetition
   3 
   4 #initialization phase
   5 total = 0   #sum of grades
   6 gradeCounter = 1    #number of grades entered
   7 
   8 #processing phase
   9 while gradeCounter <= 10:
  10     grade = raw_input("Enter grade:")
  11     grade = int(grade)
  12     total = total + grade
  13     gradeCounter = gradeCounter + 1
  14 
  15 #termination phase
  16 average = float(total) / 10     #covert integer to float
  17 print "Class average is", average

Chapter 3.2 Class average program with sentinel-controlled repetition

   1 #chapter3.2
   2 #Class average program with sentinel-controlled repetition
   3 
   4 #initialization phase
   5 total = 0   #sum of grade
   6 gradeCounter = 0    #number of grades entered
   7 
   8 #processing phase
   9 grade = raw_input("Enter grade,-1 to end:") #get one grade
  10 grade = int(grade)
  11 
  12 while grade !=-1:
  13     total = total + grade
  14     gradeCounter = gradeCounter + 1
  15     grade = raw_input("Enter grade,-1 to end:")
  16     grade = int(grade)
  17 
  18 #termination phase
  19 if gradeCounter != 0:
  20     average = float(total) / gradeCounter
  21     print "Class average is", average
  22 else:
  23     print "No grade were entered"

Chapter 3.3 Analysis of examination results

   1 #chapter 3.3
   2 #Analysis of examination results
   3 
   4 #initialize variables
   5 passes = 0
   6 failures = 0
   7 studentCounter = 1
   8 
   9 #process 10 students
  10 while studentCounter <= 10:
  11     result = raw_input("Enter result(1=pass,2=fail):")
  12     result = int(result)
  13 
  14     if result == 1:
  15         passes = passes + 1
  16     else:
  17         failures = failures + 1
  18 
  19     studentCounter = studentCounter + 1
  20 
  21 #termination phase
  22 print "Passed", passes
  23 print "Failed", failures
  24 
  25 if passes > 8:
  26     print "Raise tuition"

Chapter 4.1 Recursive factorial function

   1 #chapter 4.1
   2 #Recursive factorial function.
   3 
   4 def factorial(number):
   5     if number <=1:
   6         return 1
   7     else:
   8         return number * factorial(number - 1)   #recursive call
   9 
  10 for i in range(11):
  11     print "%2d! = %d" % (i, factorial(i))

Chapter 4.2 Recursive fibonacci function 0,1,1,2,3,5,8,13,21

   1 #chapter4.2
   2 #Recursive fibonacci function  0,1,1,2,3,5,8,13,21
   3 
   4 def fibonacci(n):
   5     if n == 0 or n == 1:
   6         return n
   7     else:
   8         return fibonacci(n - 1) + fibonacci(n - 2)
   9 
  10 number = int(raw_input("Enter the integer:"))
  11 
  12 if number > 0:
  13     result = fibonacci(number)
  14     print "Fibonacci(%d) = %d" % (number, result)
  15 else:
  16     print "Cannot find the fibonacci of a negative number"

Chapter 5.1 Unpacking sequences

   1 #chapter 5.1
   2 #Unpacking sequences
   3 
   4 #create sequences
   5 aString = "abc"
   6 aList = [1,2,3]
   7 aTuple = ("a","b",1)
   8 
   9 #unpacking sequences
  10 print "unpacking string..."
  11 first,second,third = aString
  12 print "String values:", first,second,third
  13 
  14 print "\nunpacking list..."
  15 first,second,third = aList
  16 print "List values:",first,second,third
  17 
  18 print "\nunpacking tuple..."
  19 first,second,third = aTuple
  20 print "Tuple values:",first,second,third
  21 
  22 #swapping two values
  23 x = 3
  24 y = 4
  25 
  26 print "\nBefore swapping:x = %d,y = %d" % (x,y)
  27 x,y = y,x   #swapping variables
  28 print "After swapping:x = %d, y = %d" % (x,y)

Chapter 7.1 simple definition of class Time

   1 #chapter 7.1
   2 #Simple definition of class Time.
   3 
   4 class Time:
   5     """Time abstract data type definition"""
   6     def __init__(self):
   7         """Initializes hour,minute and second to zero"""
   8         self.hour = 0
   9         self.minute = 0
  10         self.second = 0
  11 
  12     def printMilitray(self):
  13         """Prints object of class Time in military format"""
  14         print "%.2d:%.2d:%.2d" % (self.hour,self.minute,self.second)
  15 
  16     def printStandard(self):
  17         """Prints object of class Time in standard format"""
  18 
  19         standardTime = ""
  20 
  21         if self.hour == 0 or self.hour == 12:
  22             standardTime += "12:"
  23         else:
  24             standardTime += "%d:" % (self.hour % 12)
  25 
  26         standardTime += "%.2d:%.2d" % (self.minute,self.second)
  27 
  28         if self.hour < 12:
  29             standardTime += "AM"
  30         else:
  31             standardTime += "PM"
  32 
  33         print standardTime

Chapter 7.2 Class Time with accessor methods

   1 #chapter 7.2
   2 #Class Time with accessor methods.
   3 
   4 class Time:
   5     """Class Time with accessor methods"""
   6 
   7     def __init__(self):
   8         """Time constructor initializes each data member to zero"""
   9 
  10         self.__hour = 0     #private value,change to _Time__hour.
  11         self._minute = 0    #public value
  12         self._second = 0
  13 
  14     def setTime(self,hour,minute,second):
  15         """Set values of hour,minute,and second"""
  16 
  17         self.setHour( hour )
  18         self.setMinute( minute )
  19         self.setSecond( second )
  20 
  21     def setHour( self,hour):
  22         """Set hour value"""
  23 
  24         if 0 <= hour < 24:
  25             self._hour = hour
  26         else:
  27             raise ValueError,"Invalid hour value: %d" % hour
  28 
  29     def setMinute( self,minute ):
  30         """Set minute value"""
  31 
  32         if 0 <= minute < 60:
  33             self._minute = minute
  34         else:
  35             raise ValueError,"Invalid minute value: %d" % minute
  36 
  37     def setSecond ( self,second ):
  38         """Set second value"""
  39 
  40         if 0 <= senond <60:
  41             self._second = second
  42         else:
  43             raise ValueError,"Invalid second value: %d" % second
  44 
  45     def getHour( self ):
  46         """Get hour value"""
  47 
  48         return self._hour
  49 
  50     def getMinute( self ):
  51         """Get minute value"""
  52 
  53         return self._minute
  54 
  55     def getSecond( self ):
  56         """Get second value"""
  57 
  58         return self._second
  59 
  60     def printMilitray(self):
  61         """Prints object of class Time in military format"""
  62         print "%.2d:%.2d:%.2d" % (self._hour,self._minute,self._second)
  63 
  64     def printStandard(self):
  65         """Prints object of class Time in standard format"""
  66 
  67         standardTime = ""
  68 
  69         if self._hour == 0 or self._hour == 12:
  70             standardTime += "12:"
  71         else:
  72             standardTime += "%d:" % (self._hour % 12)
  73 
  74         standardTime += "%.2d:%.2d" % (self._minute,self._second)
  75 
  76         if self._hour < 12:
  77             standardTime += "AM"
  78         else:
  79             standardTime += "PM"
  80 
  81         print standardTime

Chapter 7.3 Class Time with default constructor

   1 #chapter 7.3
   2 #Class Time with default constructor.
   3 #use private value
   4 
   5 class Time:
   6     """Class Time with accessor methods"""
   7 
   8     def __init__(self, hour = 0, minute = 0, second = 0):
   9         """Time constructor initializes each data member to zero"""
  10 
  11         self.setTime( hour, minute, second )
  12 
  13     def setTime(self, hour, minute, second):
  14         """Set values of hour,minute,and second"""
  15 
  16         self.setHour( hour )
  17         self.setMinute( minute )
  18         self.setSecond( second )
  19 
  20     def setHour( self,hour):
  21         """Set hour value"""
  22 
  23         if 0 <= hour < 24:
  24             self.__hour = hour
  25         else:
  26             raise ValueError,"Invalid hour value: %d" % hour
  27 
  28     def setMinute( self,minute ):
  29         """Set minute value"""
  30 
  31         if 0 <= minute < 60:
  32             self.__minute = minute
  33         else:
  34             raise ValueError,"Invalid minute value: %d" % minute
  35 
  36     def setSecond ( self,second ):
  37         """Set second value"""
  38 
  39         if 0 <= senond <60:
  40             self.__second = second
  41         else:
  42             raise ValueError,"Invalid second value: %d" % second
  43 
  44     def getHour( self ):
  45         """Get hour value"""
  46 
  47         return self.__hour
  48 
  49     def getMinute( self ):
  50         """Get minute value"""
  51 
  52         return self.__minute
  53 
  54     def getSecond( self ):
  55         """Get second value"""
  56 
  57         return self.__second
  58 
  59     def printMilitray(self):
  60         """Prints object of class Time in military format"""
  61         print "%.2d:%.2d:%.2d" % (self.__hour,self.__minute,self.__second)
  62 
  63     def printStandard(self):
  64         """Prints object of class Time in standard format"""
  65 
  66         standardTime = ""
  67 
  68         if self.__hour == 0 or self.__hour == 12:
  69             standardTime += "12:"
  70         else:
  71             standardTime += "%d:" % (self.__hour % 12)
  72 
  73         standardTime += "%.2d:%.2d" % (self.__minute,self.__second)
  74 
  75         if self.__hour < 12:
  76             standardTime += "AM"
  77         else:
  78             standardTime += "PM"
  79 
  80         print standardTime

Chapter 7.4 Class Employee with class attribute count

   1 #chapter 7.4
   2 #Class Employee with class attribute count
   3 
   4 class Employee:
   5     """Represents an employee"""
   6 
   7     count = 0   #class attribute
   8 
   9     def __init__( self,first,last ):
  10         """Initializes firstName,lastName and increments count"""
  11 
  12         self.firstName = first
  13         self.lastNmae = last
  14 
  15         Employee.count += 1     #increment class attribute
  16 
  17         print "Employee constructor for %s ,%s" % (self.lastNmae,self.firstName)
  18 
  19     def __del__( self ):
  20         """Decrements count and prints message"""
  21 
  22         Employee.count -= 1     #decrement class attribute
  23 
  24         print "Eemployee destructor for %s, %s" % ( self.lastNmae, self.firstName )

Chapter 8.1 Representation of phone number in USA format: (xxx) xxx-xxxx

   1 #chapter 8.1
   2 #Representation of phone number in USA format: (xxx) xxx-xxxx.
   3 
   4 class PhoneNumber:
   5     """Simple class to represent phone number in USA format"""
   6 
   7     def __init__( self, number ):
   8         """Accepts string in form (xxx) xxx-xxxx"""
   9 
  10         self.areaCode = number[ 1:4 ]   #3-digit area code
  11         self.exchange = number[ 6:9 ]   #3-digit exchange
  12         self.line = number[ 10:14 ]     #4-digit line
  13 
  14     def __str__( self ):
  15         """Informal string representation"""
  16 
  17         return "(%s) %s-%s" % (self.areaCode, self.exchange, self.line)
  18 
  19 def test():
  20     newNumber = raw_input("Enter phone in the form(123) 456-7890:")
  21     phone = PhoneNumber ( newNumber )
  22     print "the phone number is:"
  23     print phone     #invokes phone.__str__()
  24 
  25 if __name__ == "__main__":
  26     test()

Chapter 8.2 Class Time with customized attribute access

   1 #chapter8.2
   2 #Class Time with customized attribute access.
   3 
   4 class Time:
   5     """Class Time with customized attribute access"""
   6 
   7     def __init__( self, hour = 0, minute = 0, second = 0 ):
   8         """Time constructor initializes each data member to zero"""
   9 
  10         self.hour = hour        #each statement invokes __setattr__
  11         self.minute = minute
  12         self.second = second
  13 
  14     def __setattr__( self, name, value ):
  15         """Assigns a value to an attribute"""
  16 
  17         if name == "hour":
  18             if 0 <= value < 24:
  19                 self.__dict__[ "_hour" ] = value
  20             else:
  21                 raise ValueError, "Invalid hour value: %d" % value
  22         elif name == "minute" or name == "second":
  23                 if 0 <= value < 60:
  24                     self.__dict__[ "_" + name ] = value
  25                 else:
  26                    raise ValueError, "Invalid %s value: %d" % ( name, value )
  27         else:
  28             self.__dict__[ name ] = value
  29 
  30     def __getattr__( self, name ):
  31         """Performs lookup for unrecognized attribute name"""
  32 
  33         if name == "hour":
  34             return self._hour
  35         elif name == "minute":
  36             return self._minute
  37         elif name == "second":
  38             return self._second
  39         else:
  40             raise AttributeError, name
  41 
  42     def __str__( self ):
  43         """Returns Time object string in military format"""
  44 
  45         return "%.2d:%.2d:%.2d" % ( self._hour, self._minute,self._second )

Chapter 9.1 derived class inheriting from a base class

   1 #chapter 9.1
   2 #derived class inheriting from a base class.
   3 
   4 import math
   5 
   6 class Point:
   7     """Class that represents geometric point"""
   8 
   9     def __init__( self, xValue = 0, yValue = 0 ):
  10         """Point constructor takes x and y coordinates"""
  11 
  12         self.x = xValue
  13         self.y = yValue
  14 
  15 class Circle(Point):
  16     """Class that repesents a circle"""
  17 
  18     def __init__( self, x = 0, y = 0, radiusValue = 0.0 ):
  19         """Circle constructor takes x and y coordinates of center point and radius"""
  20 
  21         Point.__init__( self, x, y )    #call base-class constructor
  22         self.radius = float( radiusValue )
  23 
  24     def area ( self ):
  25         """Computes area of a Circle"""
  26 
  27         return math.pi * self.radius ** 2
  28 
  29 #main program
  30 
  31 #examine classes Point and Circle
  32 print "Point bases:",Point.__bases__
  33 print "Circle bases:",Circle.__bases__
  34 
  35 #demonstrate class relationships with built-in function issubclass
  36 print "\nCircle is a subclass of Point:", issubclass(Circle, Point)
  37 print "Point is a subclass of Circle:", issubclass(Point, Circle)
  38 
  39 point = Point(30,50)    #create Point object
  40 circle = Circle(120,89,2.7) #create Circle object
  41 
  42 #demonstrate object relationship with built-in function isinstance
  43 print "\ncircle is a Point object:", isinstance( circle, Point )
  44 print "point is a Circle object:", isinstance( point, Circle )
  45 
  46 #print Point and Circle object
  47 print "\npoint members:\n\t", point.__dict__
  48 print "circle members:\n\t", circle.__dict__
  49 
  50 print "\nArea of circle is :", circle.area()

Chapter 9.2 Overriding base-class methods

   1 #chapter9.2
   2 #Overriding base-class methods
   3 
   4 class Employee:
   5     """Class to represent an employee"""
   6 
   7     def __init__( self, first, last ):
   8         """Employee constructor takes first and last name"""
   9 
  10         self.firstName = first
  11         self.lastName = last
  12 
  13     def __str__( self ):
  14         """String representation of an Employee"""
  15 
  16         return "%s %s" % ( self.firstName, self.lastName )
  17 
  18 class HourlyWorker ( Employee ):
  19     """Class to represent an employee paid by hour"""
  20 
  21     def __init__( self, first, last, initHours, initWage ):
  22         """Constructor for HourlyWorker,takes first and last name,
  23         initial number of hours and initial wage"""
  24 
  25         Employee.__init__( self, first, last )
  26         self.hours = float( initHours )
  27         self.wage = float( initWage )
  28 
  29     def getPay( self ):
  30         """Calculates HourlyWorker's weekly pay"""
  31 
  32         return self.hours * self.wage
  33 
  34     def __str__( self ):
  35         """String representation of HourlyWorker,overriding \
  36         the __str__ method of Employee """
  37 
  38         print "HourlyWorker.__str__ is executing"
  39 
  40         return "%s is an hourly worker with pay of $%.2f" % \
               ( Employee.__str__( self ), self.getPay() )
  41         #Employee.__str__( self ) call the base class to print firstName and lastName.
  42         #self.getPay() a new function.
  43 
  44 #main program
  45 
  46 hourly = HourlyWorker("bob", "smith", 40.0, 10.00 )
  47 
  48 #invoke __str__ method several ways
  49 print "Calling __str__ several ways ..."
  50 print hourly    #invoke __str__ implicitly
  51 print hourly.__str__()  #invoke __str__ explicitly
  52 print HourlyWorker.__str__( hourly ) #explicit, unbound call

Chapter 9.3 Creating a class hierarchy with an abstract base class

   1 #chapter9.3
   2 #Creating a class hierarchy with an abstract base class.
   3 
   4 class Employee:
   5     """Abstract base class Employee"""
   6 
   7     def __init__( self, first, last ):
   8         """Employee constructor,takes first name and last name\
   9         NOTE: Cannot create object of class Employee"""
  10 
  11         if self.__class__ == Employee:
  12             raise NotImplementedError, "Cannot create object of class Employee"
  13 
  14         self.firstName = first
  15         self.lastName = last
  16 
  17     def __str__( self ):
  18         """String representation of Employee"""
  19 
  20         return "%s %s" % ( self.firstName, self.lastName )
  21 
  22     def _checkPositive( self, value ):
  23         """Utility method to ensure a value is positive"""
  24 
  25         if value < 0:
  26             raise ValueError, "Attribute value (%s) must be positive" % value
  27         else:
  28             return value
  29 
  30     def earnings( self ):
  31         """Abstract method;derived classes must override"""
  32 
  33         raise NotImplementedError, "Cannot call abstract method"
  34 
  35 class Boss( Employee ):
  36     """Boss class, inherits from Employee"""
  37 
  38     def __init__( self, first, last, salary ):
  39         """Boss constructor,takes first and last names and salary"""
  40 
  41         Employee.__init__( self, first, last )
  42         self.weeklySalary = self._checkPositive( float( salary ) )
  43 
  44     def earnings( self ):
  45         """Compute the boss's pay"""
  46 
  47         return self.weeklySalary
  48 
  49     def __str__( self ):
  50         """String representation of Boss"""
  51 
  52         return "%17s: %s" % ( "Boss", Employee.__str__(self) )
  53 
  54 class CommissionWorker ( Employee ):
  55     """CommissionWorker class,inherits from Employee"""
  56 
  57     def __init__( self, first, last, salary, commission, quantity ):
  58         """CommissionWorker constructor,takes first and last names,\
  59         salary,commission and quantity"""
  60 
  61         Employee.__init__( self, first, last )
  62         self.salary = self._checkPositive( float( salary ))
  63         self.commission = self._checkPositive( float( commission))
  64         self.quantity = self._checkPositive( quantity )
  65 
  66     def earnings( self ):
  67         """Compute the CommissionWorker's pay"""
  68 
  69         return self.salary + self.commission * self.quantity
  70 
  71     def __str__( self ):
  72         """Srting representation of CommissionWorker"""
  73 
  74         return "%17s: %s" % ("Commission Worker", Employee.__str__( self ))
  75 
  76 class PieceWorker ( Employee ):
  77     """PieceWorker class,inherits from Employee"""
  78 
  79     def __init__( self, first, last, wage, quantity ):
  80         """PieceWorker constructor,takes first and last names,wage\
  81          per piece and quantity"""
  82 
  83         Employee.__init__( self, first,last )
  84         self.wagePerPiece = self._checkPositive( float( wage ) )
  85         self.quantity = self._checkPositive( quantity )
  86 
  87     def earnings( self ):
  88         """Compute PieceWorker's pay"""
  89 
  90         return self.quantity * self.wagePerPiece
  91 
  92     def __str__( self ):
  93         """Srting representation of PieceWorker"""
  94 
  95         return "%17s: %s" % ( "PieceWorker", Employee.__str__( self ) )
  96 
  97 class HourlyWorker( Employee ):
  98     """HourlyWorker class, inherits from Employee"""
  99 
 100     def __init__( self, first, last, wage, hours ):
 101         """HourlyWorker constructor,takes first and last names,wage \
 102         per hour and hours worked"""
 103 
 104         Employee.__init__( self, first, last )
 105         self.wage = self._checkPositive( float( wage ) )
 106         self.hours = self._checkPositive( float( hours ) )
 107 
 108     def earnings( self ):
 109         """Compute HourlyWorker's pay"""
 110 
 111         if self.hours <= 40:
 112             return self.wage * self.hours
 113         else:
 114             return 40 * self.wage + ( self.hours - 40 ) * self.wage * 1.5
 115 
 116     def __str__( self ):
 117         """Srting representation of HourlyWorker"""
 118 
 119         return "%17s: %s" % ( "HourlyWorker", Employee.__str__( self ) )
 120 
 121 #main program
 122 
 123 #create list of Employee
 124 employees = [ Boss( "John", "Smith", 800.00 ),
 125              CommissionWorker( "Sue", "Jones", 200.0, 3.0, 150 ),
 126              PieceWorker( "Bob", "Lewis", 2.5, 200 ),
 127              HourlyWorker( "Karem", "Price", 13.75, 40 ) ]
 128 
 129 #print Employee and compute earnings
 130 for employee in employees:
 131     print "%s earned $%.2f" % ( employee, employee.earnings() )

Chapter 9.4 Class Employee with a static method

   1 #chapter 9.4
   2 #Class Employee with a static method.
   3 
   4 class Employee:
   5     """Employee class with static method isCrowded"""
   6 
   7     numberOfEmployees = 0   #number of Employee created
   8     maxEmployees = 10       #maximun number of comfortable employees
   9 
  10     def isCrowded():
  11         """Static method returns true if the employee are crowded"""
  12 
  13         return Employee.numberOfEmployees > Employee.maxEmployees
  14 
  15 #create static method
  16     isCrowded = staticmethod( isCrowded )
  17 
  18     def __init__( self, firstName, lastName ):
  19         """Employee constructor,takes first and last names"""
  20 
  21         self.first = firstName
  22         self.last = lastName
  23         Employee.numberOfEmployees += 1
  24 
  25     def __del__( self ):
  26         """Employee destructor"""
  27 
  28         Employee.numberOfEmployees -= 1
  29 
  30     def __str__( self ):
  31         """String representation of Employee"""
  32 
  33         return "%s %s" % (self.first, self.last)
  34 
  35 #main program
  36 
  37 def main():
  38     answers = [ "No", "Yes" ]   #responses to isCrowded
  39     employeeList = []           #list of objects of class Employee
  40 
  41     #call static method using class
  42     print "Employee are crowded?",
  43     print answers [ Employee.isCrowded() ]
  44 
  45     print "\nCreating 11 objects of class Employee..."
  46 
  47     #create 11 objects of class Employee
  48     for i in range(11):
  49         employeeList.append( Employee( "John","Doe" + str(i) ) )
  50 
  51     #call static method using object
  52 
  53     print "Employee are crowded?",
  54     print answers [ employeeList[i].isCrowded() ]
  55 
  56     print "\nremoving one employee..."
  57     del employeeList[0]
  58 
  59     print "Employees are crowded?", answers [ Employee.isCrowded() ]
  60 
  61 if __name__ == "__main__":
  62         main()

Chapter 9.5 Class that defines method __getattribute__

   1 #chapter 9.5
   2 #Class that defines method __getattribute__
   3 
   4 class DemoAccess( object ):
   5     """class to demonstrate when method __getattribute__ executes"""
   6 
   7     def __init__(self):
   8         """demoaccess constructor,initializes attribute value"""
   9 
  10         self.value = 1
  11 
  12     def __getattribute__( self, name ):
  13         """Executes form every attribute access"""
  14 
  15         print "__getattribute__ executing..."
  16         print "\nClient attempt to access attribute:",name
  17 
  18         return object.__getattribute__( self, name )
  19 
  20     def __getattr__( self, name ):
  21         """Executes when client access attribute not in __dict__"""
  22 
  23         print "__getattr__ executing..."
  24         print "\tClient attempt to access non-existent attribute:", name
  25 
  26         raise AttributeError, "Object has no attribute %s " % name

Chapter 9.6 simple class with slots

   1 #chapter 9.6
   2 #simple class with slots
   3 
   4 class PointWithoutSlots:
   5     """program can add attribute to objects of this class"""
   6 
   7     def __init__( self, xValue = 0.0, yValue = 0.0 ):
   8 
   9         self.x = float( xValue )
  10         self.y = float( yValue )
  11 
  12 class PointWithSlots( object ):
  13     """program cannot add attribute to objects of this class"""
  14 
  15 #PointWithSlots objects can contain only attributes x and y
  16     __slots__ = [ "x", "y" ]
  17 
  18     def __init__( self, xValue = 0.0, yValue = 0.0 ):
  19 
  20         self.x = float( xValue )
  21         self.y = float( yValue )
  22 
  23 #main program
  24 
  25 def main():
  26     noSlots = PointWithoutSlots()
  27     slots = PointWithSlots()
  28 
  29     for point in [ noSlots, slots ]:
  30         print "\nProcessing an object of class", point.__class__
  31 
  32         print "The current value of point.x is:", point.x
  33         newValue = float( raw_input("Eenter new x coordinate:") )
  34         print "Attempting to set new x-coordinate value..."
  35 
  36 #logic error: create new attribute called X, instead of changing the value of attribute X
  37         point.X = newValue
  38 
  39 #output unchanged attribute x
  40         print "the new value of point.x is :", point.x
  41 
  42 if __name__ == "__main__":
  43     main()

Chapter 9.7 Class Time with properties

   1 #chapter 9.7
   2 #Class Time with properties
   3 
   4 class Time( object ):
   5     """Class Time with hour, minute and second properties"""
   6 
   7     def __init__( self, hourValue, minuteValue, secondValue ):
   8         """Time constructor,takes hour, minute and second"""
   9 
  10         self.__hour = hourValue
  11         self.__minute = minuteValue
  12         self.__second = secondValue
  13 
  14     def __str__( self ):
  15         """String representation of an object of class Time"""
  16 
  17         return "%.2d:%.2d:%.2d" % ( self.__hour, self.__minute, self.__second )
  18 
  19     def deleteValue( self ):
  20         """Delete method for Time properties"""
  21 
  22         raise TypeError, "Cannot delete attribute"
  23 
  24     def setHour( self, value ):
  25         """set method for hour attribute"""
  26 
  27         if 0 <= value < 24:
  28             self.__hour =value
  29         else:
  30             raise ValueError, "Hour (%d) must be in range 0-23, inclusive" % value
  31 
  32     def getHour( self ):
  33         """get method for hour attribute"""
  34 
  35         return self.__hour
  36 
  37 #create hour property.can use "time.hour = 11" to set the hour's value or "print time.hour" to print hour's value.
  38     hour = property( getHour,setHour,deleteValue, "hour" )
  39 
  40     def setMinute( self, value ):
  41         """set method for minute attribute"""
  42 
  43         if 0 <= value < 60:
  44             self.__minute =value
  45         else:
  46             raise ValueError, "Minute (%d) must be in range 0-59, inclusive" % value
  47 
  48     def getMinute( self ):
  49         """get method for minute attribute"""
  50 
  51         return self.__minute
  52 
  53 #create minute property
  54     minute = property( getMinute, setMinute, deleteValue, "minute" )
  55 
  56     def setSecond( self, value ):
  57         """set method for second attribute"""
  58 
  59         if 0 <= value < 60:
  60             self.__second =value
  61         else:
  62             raise ValueError, "Second (%d) must be in range 0-59, inclusive" % value
  63 
  64     def getSecond( self ):
  65         """get method for second attribute"""
  66 
  67         return self.__second
  68 
  69 #create second property
  70     second = property( getSecond, setSecond, deleteValue, "second" )

Chapter 10.1 Label demonstration

   1 #chapter 10.1
   2 #Label demonstration.
   3 
   4 from Tkinter import *
   5 
   6 class LabelDemo( Frame ):
   7     """Demonstrate Labels"""
   8 
   9     def __init__( self ):
  10         """Create three labels and pack them"""
  11 
  12         Frame.__init__( self,)  #initializes Frame object
  13 
  14 #frame fills all available space
  15         self.pack( expand = YES, fill = BOTH )
  16         self.master.title( "myLabel" )
  17 
  18         self.Label1 = Label( self, text = "Label with text" )
  19 #resize frame to accommodate Label
  20         self.Label1.pack()
  21 
  22         self.Label2 = Label( self, text = "Labels with text and bitmap" )
  23 
  24 #insert Lable1 against left side of frame
  25         self.Label2.pack( side = LEFT )
  26 
  27 #using default bitmap image as label
  28         self.Label3 = Label( self, bitmap = "warning" )
  29         self.Label3.pack( side = LEFT )
  30 
  31 def main():
  32     LabelDemo().mainloop()  #starts event loop
  33 
  34 if __name__ == "__main__":
  35     main()

Chapter 10.2 Entry components and event binding demostration

   1 # chapter 10.2
   2 #Entry components and event binding demostration
   3 
   4 from Tkinter import *
   5 from tkMessageBox import *
   6 
   7 class EntryDemo( Frame ):
   8 
   9     def __init__( self ):
  10         """create,pack and bind events to four Entrys"""
  11 
  12         Frame.__init__( self )
  13         self.pack( expand = YES, fill = BOTH )
  14         self.master.title( "Testing Entry Components")
  15         self.master.geometry( "325x100" )    #width X length
  16 
  17         self.frame1 = Frame( self )
  18         self.frame1.pack( pady = 5 )
  19 
  20         self.text1 = Entry( self.frame1, name = "text1" )
  21 
  22 #bind the Entry component to event
  23         self.text1.bind( "<Return>", self.showContents )
  24         self.text1.pack( side = LEFT, padx = 5 )
  25 
  26         self.text2 = Entry( self.frame1, name = "text2" )
  27 
  28 #insert text into Entry component text2
  29         self.text2.insert( INSERT, "Enter text here" )
  30         self.text2.bind( "<Return>", self.showContents )
  31         self.text2.pack( side = LEFT, padx = 5 )
  32 
  33         self.frame2 = Frame( self )
  34         self.frame2.pack ( pady = 5 )
  35 
  36         self.text3 = Entry( self.frame2, name = "text3" )
  37         self.text3.insert( INSERT, "uneditable text field")
  38 
  39 #probibit user from altering text in Entry component text3
  40         self.text3.config( state =DISABLED )
  41         self.text3.bind( "<Return>", self.showContents )
  42         self.text3.pack( side = LEFT, padx = 5 )
  43 
  44 #text in Entry component text4 appears as *
  45         self.text4 = Entry( self.frame2, name = "text4", show = "*" )
  46         self.text4.insert( INSERT, "Hidden text" )
  47         self.text4.bind( "<Return>",self.showContents )
  48         self.text4.pack( side = LEFT,padx = 5 )
  49 
  50     def showContents( self,event ):
  51         """disaplay the contents of the Entry"""
  52 
  53 #acquire name of Entry component that generated event
  54         theName = event.widget.winfo_name()
  55 
  56 #acquire contents of Entry component that generated event
  57         theContents = event.widget.get()
  58         showinfo( "Message",theName + ":" + theContents )
  59 
  60 def main():
  61     EntryDemo().mainloop()
  62 
  63 if __name__ == "__main__":
  64     main()

Chapter 10.3 Button demonstration

   1 #chapger10.3
   2 #Button demonstration
   3 
   4 from Tkinter import *
   5 from tkMessageBox import *
   6 
   7 class PlainAndFancy( Frame ):
   8     """Create one plain and one fancy button"""
   9 
  10     def __init__( self ):
  11         """Create two buttons,pack them and bind events"""
  12 
  13         Frame.__init__( self )
  14         self.pack( expand = YES , fill = BOTH )
  15         self.master.title( "Buttons" )
  16 
  17         #create button with text
  18         self.plainButton = Button( self, text = "Plain Button", fg = "red", bg = "blue", command = self.pressedPlain )
  19         self.plainButton.bind( "<Enter>", self.rolloverEnter )
  20         self.plainButton.bind( "<Leave>", self.rolloverLeave )
  21         self.plainButton.pack( side = LEFT, padx = 5, pady = 5 )
  22 
  23         #create button with image
  24         self.myImage = PhotoImage( file = "c:\logo1.gif" )
  25         self.fancyButton = Button( self, image = self.myImage, bg = "blue", command = self.pressedFancy )
  26         self.fancyButton.bind( "<Enter>", self.rolloverEnter )
  27         self.fancyButton.bind( "<Leave>", self.rolloverLeave )
  28         self.fancyButton.pack( side = LEFT, padx = 5, pady = 5 )
  29 
  30     def pressedPlain( self ):
  31         showinfo( "Message", "You pressed:Plain Button" )
  32 
  33     def pressedFancy( self ):
  34         showinfo( "Message", "You pressed:Fancy Button" )
  35 
  36     def rolloverEnter ( self, event ):
  37         event.widget.config( relief = GROOVE )
  38 
  39     def rolloverLeave ( self, event ):
  40         event.widget.config( relief = RAISED )
  41 
  42 def main():
  43     PlainAndFancy().mainloop()
  44 
  45 if __name__=="__main__":
  46     main()

Chapter 10.4 Checkbuttons demostration

   1 #chapter10.4
   2 #Checkbuttons demostration.
   3 
   4 from Tkinter import *
   5 
   6 class CheckFont( Frame ):
   7     """An area of text with Checkbutton controlled font"""
   8 
   9     def __init__( self ):
  10         """Create an Entry and two Checkbuttons"""
  11 
  12         Frame.__init__( self )
  13         self.pack( expand = YES, fill = BOTH )
  14         self.master.title( "Checkbutton Demo" )
  15 
  16         self.frame1 = Frame( self )
  17         self.frame1.pack()
  18 
  19         self.text = Entry( self.frame1, width = 40, font = "Arial 10" )
  20         self.text.insert ( INSERT, "Watch the font style change" )
  21         self.text.pack( padx = 5, pady = 5 )
  22 
  23         self.frame2 = Frame( self )
  24         self.frame2.pack()
  25 
  26         #Create boolean variable
  27         self.boldOn = BooleanVar()
  28 
  29         #Create "Bold" checkbutton
  30         self.checkBold = Checkbutton( self.frame2, text = "Bold", variable = self.boldOn,
  31                                       command = self.changeFont )
  32         self.checkBold.pack( side = LEFT, padx = 5, pady = 5 )
  33 
  34         #Create boolean variable
  35         self.italicOn = BooleanVar()
  36 
  37         #Create "Italic" checkbutton
  38         self.checkItalic = Checkbutton ( self.frame2, text = "Italic", variable = self.italicOn,
  39                                          command = self.changeFont )
  40         self.checkItalic.pack( side = LEFT, padx =5, pady = 5 )
  41 
  42     def changeFont( self ):
  43         """Change the font based on selected Checkbuttons"""
  44 
  45         desiredFont = "Arial 10"
  46 
  47         if self.boldOn.get():
  48             desiredFont += " bold"
  49 
  50         if self.italicOn.get():
  51             desiredFont += " italic"
  52 
  53         self.text.config( font = desiredFont )
  54 
  55 def main():
  56     CheckFont().mainloop()
  57 
  58 if __name__ =="__main__":
  59     main()

Chapter 10.5 Radiobuttons demonstration

   1 #chapter10.5
   2 #Radiobuttons demonstration.
   3 
   4 from Tkinter import *
   5 
   6 class RadioFont( Frame ):
   7     """An area of text with Radiobutton controlled font"""
   8 
   9     def __init__( self ):
  10         """Create an Entry and Four Radiobuttons"""
  11 
  12         Frame.__init__( self )
  13         self.pack( expand = YES, fill = BOTH )
  14         self.master.title( "Radiobutton Demo" )
  15 
  16         self.frame1 = Frame( self )
  17         self.frame1.pack()
  18 
  19         self.text = Entry( self.frame1, width = 40, font = "Arial 10" )
  20         self.text.insert( INSERT, "Watch the font style change" )
  21         self.text.pack( padx = 5, pady = 5 )
  22 
  23         self.frame2 = Frame( self )
  24         self.frame2.pack()
  25 
  26         fontSelections = [ "Plain", "Bold", "Italic", "Bold/Italic" ]
  27         self.chosenFont = StringVar()
  28 
  29         #initial selection
  30         self.chosenFont.set( fontSelections [ 0 ] )
  31 
  32         #create group of Radiobutton components with same variable
  33         for style in fontSelections:
  34             aButton = Radiobutton( self.frame2, text = style, variable = self.chosenFont,
  35                                value = style, command = self.changeFont )
  36             aButton.pack( side = LEFT, padx = 5, pady = 5 )
  37 
  38     def changeFont( self ):
  39         """change the font based on selected Radiobutton"""
  40 
  41         desiredFont = "Arial 10"
  42 
  43         if self.chosenFont.get() == "Bold":
  44             desiredFont += " bold"
  45         elif self.chosenFont.get == " Italic":
  46             desiredFont += " italic"
  47         elif self.chosenFont.get() == "Bold/Italic":
  48             desiredFont += " bold italic"
  49 
  50         self.text.config( font = desiredFont )
  51 
  52 def main():
  53     RadioFont().mainloop()
  54 
  55 if __name__ == "__main__":
  56     main()

Chapter 10.6 Mouse events example

   1 #chapter10.6
   2 #Mouse events example.
   3 
   4 from Tkinter import *
   5 
   6 class MouseLocation( Frame ):
   7     """Demonstrate binding mouse events"""
   8 
   9     def __init__( self ):
  10         """Create a Label,pack it and bind mouse events"""
  11 
  12         Frame.__init__( self )
  13         self.pack( expand = YES, fill = BOTH )
  14         self.master.title( "Demonstrating Mouse Events" )
  15         self.master.geometry( "275x100" )
  16 
  17         self.mousePosition = StringVar() # display mouse position
  18         self.mousePosition.set( "Mouse outside window" )
  19         self.positionLabel = Label( self, textvariable = self.mousePosition )
  20         self.positionLabel.pack( side = BOTTOM )
  21 
  22         #bind mouse events to windows
  23         self.bind( "<Button-1>", self.buttonPressed )
  24         self.bind( "<ButtonRelease-1>", self.buttonReleased )
  25         self.bind( "<Enter>", self.enteredWindow )
  26         self.bind( "<Leave>", self.exitedWindow )
  27         self.bind( "<B1-Motion>", self.mouseDragged )
  28 
  29     def buttonPressed( self, event ):
  30         """Display coordinates of button press"""
  31 
  32         self.mousePosition.set( "Pressed at [ " + str( event.x ) + ", " + str( event.y) + " ]" )
  33 
  34     def buttonReleased( self, event ):
  35         """Display coordinates of button release"""
  36 
  37         self.mousePosition.set( "Released at [ " + str( event.x ) +", " + str( event.y ) + " ]" )
  38 
  39     def enteredWindow( self, event ):
  40         """Display message that mouse has entered window"""
  41 
  42         self.mousePosition.set( "Mouse in window" )
  43 
  44     def exitedWindow( self,event ):
  45         """Dispaly message that mouse has left window"""
  46 
  47         self.mousePosition.set( "Mouse outside window" )
  48 
  49     def mouseDragged( self, event ):
  50         """Display coordinates of mouse being moved"""
  51 
  52         self.mousePosition.set( "Dragged at [ " + str( event.x) + ", " + str(event.y) + " ] " )
  53 
  54 def main():
  55     MouseLocation().mainloop()
  56 
  57 if __name__ == "__main__":
  58     main()

Chapter 10.7 Binding keys to keyboard events

   1 #chapter10.7
   2 #Binding keys to keyboard events.
   3 
   4 from Tkinter import *
   5 
   6 class KeyDemo( Frame ):
   7     """Demonstrate keystroke events"""
   8 
   9     def __init__( self ):
  10         """Create two labels and bind keystroke events"""
  11 
  12         Frame.__init__( self )
  13         self.pack( expand = YES, fill = BOTH )
  14         self.master.title( "Demonstrating Keystroke Events" )
  15         self.master.geometry( "350x100" )
  16 
  17         self.message1 = StringVar()
  18         self.line1 = Label( self, textvariable = self.message1 )
  19         self.message1.set( "Type and key or shift" )
  20         self.line1.pack()
  21 
  22         self.message2 = StringVar()
  23         self.line2 = Label( self, textvariable = self.message2 )
  24         self.message2.set( "" )
  25         self.line2.pack()
  26 
  27         #binding any key
  28         self.master.bind( "<KeyPress>", self.keyPressed )
  29         self.master.bind( "<KeyRelease>", self.keyReleased )
  30 
  31         #binding specific key
  32         self.master.bind( "<KeyPress-Shift_L>", self.shiftPressed )
  33         self.master.bind( "<KeyRelease-Shift_L>", self.shiftReleased )
  34 
  35     def keyPressed( self, event ):
  36         """Display the name of the pressed key"""
  37 
  38         self.message1.set( "Key pressed:" + event.char )
  39         self.message2.set( "This key is not left shift" )
  40 
  41     def keyReleased( self, event ):
  42         """Display the name of the released key"""
  43 
  44         self.message1.set( "Key released:" + event.char )
  45         self.message2.set( "This key is not left shift" )
  46 
  47     def shiftPressed( self, event ):
  48         """Display message that left shift was pressed"""
  49 
  50         self.message1.set( "Shift pressed" )
  51         self.message2.set( "This key is left shift" )
  52 
  53     def shiftReleased( self, event ):
  54         """Display a message that left shift was released"""
  55 
  56         self.message1.set( "Shift released" )
  57         self.message2.set( "This key is left shift" )
  58 
  59 def main():
  60     KeyDemo().mainloop()
  61 
  62 if __name__ == "__main__":
  63     main()

Chapter 10.8 pack layout manager demonstration

   1 #chapter10.8
   2 #pack layout manager demonstration.
   3 
   4 from Tkinter import *
   5 
   6 class PackDemo( Frame ):
   7     """Demonstrate some options of pack"""
   8 
   9     def __init__( self ):
  10         """Create four Button with different pack options"""
  11 
  12         Frame.__init__( self )
  13         self.master.title( "Packing Demo" )
  14         self.master.geometry( "400x150" )
  15         self.pack( expand =YES, fill = BOTH )
  16 
  17         self.button1 = Button( self, text = "Add Button", command = self.addButton )
  18 
  19         #Button component placed against top of window
  20         self.button1.pack( side = TOP )
  21 
  22         self.button2 = Button( self, text = "expand = NO, fill = BOTH" )
  23 
  24         #Button component placed against bottom of window
  25         #fills all available vertical and horizontal space
  26         self.button2.pack( side = BOTTOM, fill = BOTH )
  27 
  28         self.button3 = Button( self, text = "expand = YES, fill = X" )
  29 
  30         #Button component placed against left side of window
  31         #fills all available horizontal space
  32         self.button3.pack( side = LEFT, expand = YES, fill = X )
  33 
  34         self.button4 = Button( self, text = "expand = YES, fill = Y" )
  35 
  36         #Button component placed against right side of window
  37         #fills all available vertical space
  38         self.button4.pack( side = RIGHT, expand = YES, fill = Y )
  39 
  40     def addButton( self ):
  41         """Create and pack a new Button"""
  42 
  43         Button( self, text = "new Button" ).pack( pady = 5 )
  44 
  45 def main():
  46     PackDemo().mainloop()
  47 
  48 if __name__ == "__main__":
  49     main()

Chapter 10.9 Grid layout manager demonstration

   1 #chapter10.9
   2 #Grid layout manager demonstration.
   3 
   4 from Tkinter import *
   5 
   6 class GridDemo( Frame ):
   7     """Demonstrate the Grid geometry manager"""
   8 
   9     def __init__( self ):
  10         """Create and grid several components into the frame"""
  11 
  12         Frame.__init__( self )
  13         self.master.title( "Grid Demo" )
  14 
  15         #main frame fills entrie container,expands if necessary
  16         self.master.rowconfigure( 0, weight = 1 )
  17         self.master.columnconfigure( 0, weight = 1 )
  18         self.grid( sticky = W+E+N+S )
  19 
  20         self.text1 = Text( self, width = 15, height = 5 )
  21 
  22         #text component spans three rows and all available space
  23         self.text1.grid( rowspan = 3, sticky = W+E+N+S )
  24         self.text1.insert( INSERT, "Text1" )
  25 
  26         #place button component in first row, second column
  27         self.button1 = Button( self, text = "Button1", width = 25 )
  28         self.button1.grid( row = 0, column = 1, columnspan = 2, sticky = W+E+N+S )
  29 
  30         #place button component in second row,second column
  31         self.button2 = Button( self, text = "Button2" )
  32         self.button2.grid( row = 1, column = 1, sticky = W+E+N+S )
  33 
  34         #configure button component to fill all it allocated space
  35         self.button3 = Button( self, text = "Button3" )
  36         self.button3.grid( row = 1, column = 2, sticky = W+E+N+S )
  37 
  38         #span two columns starting in second column of first row
  39         self.button4 = Button( self, text = "Button4" )
  40         self.button4.grid( row = 2, column = 1, columnspan = 2, sticky = W+E+N+S )
  41 
  42         #place text field in fourth row to span two columns
  43         self.entry = Entry( self )
  44         self.entry.grid( row = 3, columnspan = 2, sticky = W+E+N+S )
  45         self.entry.insert( INSERT, "Entry" )
  46 
  47         #fill all available space in fourth row, third column
  48         self.text2 = Text( self, width = 2, height = 2 )
  49         self.text2.grid( row = 3, column = 2, sticky = W+E+N+S )
  50         self.text2.insert( INSERT, "Text2" )
  51 
  52         #make second row/column expand
  53         self.rowconfigure( 1, weight = 1 )
  54         self.columnconfigure( 1, weight = 1 )
  55 
  56 def main():
  57     GridDemo().mainloop()
  58 
  59 if __name__ == "__main__":
  60     main()

Chapter 10.10 Card shuffling and dealing program

   1 #chapter10.10
   2 #Card shuffling and dealing program
   3 
   4 import random
   5 from Tkinter import *
   6 
   7 class Card:
   8     """Class that represents one playing card"""
   9 
  10     #class attributes faces and suits contain strings that
  11     #correspond to card face and suit values
  12     faces = [ "Ace", "Deuce", "Three", "Four", "Five",
  13               "Six", "Seven", "Eight", "Nine", "Ten",
  14               "Jack", "Queen", "King" ]
  15     suits = [ "Hearts", "Diamonds", "Clubs", "Spades" ]
  16 
  17     def __init__( self, face, suit ):
  18         """Card constructor,takes face and suit as strings"""
  19 
  20         self.face = face
  21         self.suit = suit
  22 
  23     def __str__( self ):
  24         """String representation of a card"""
  25 
  26         return "%s of %s" % ( self.face, self.suit )
  27 
  28 class Deck( Frame ):
  29     """Class to represent a GUI card deck shuffler"""
  30 
  31     def __init__( self ):
  32         """Deck constructor"""
  33 
  34         Frame.__init__( self )
  35         self.master.title( "Card Dealing Program" )
  36 
  37         self.deck = []  #list of card objects
  38         self.currentCard = 0    #index of current card
  39 
  40         #create deck
  41         for i in range( 52 ):
  42             self.deck.append( Card( Card.faces[i % 13],Card.suits[i / 13] ) )
  43 
  44         #create buttons
  45         self.dealButton = Button( self, text = "Deal Card", width = 10, command = self.dealCard )
  46         self.dealButton.grid( row = 0, column = 0 )
  47 
  48         self.shuffleButton = Button( self, text = "Shuffle cards", width = 10, command = self.shuffle )
  49         self.shuffleButton.grid( row = 0, column = 1 )
  50 
  51         #create labels
  52         self.message1 = Label( self, height = 2, text = "Welcome to Card Dealer!" )
  53         self.message1.grid( row= 1, columnspan = 2 )
  54 
  55         self.message2 = Label( self, height = 2, text = "Deal card or shuffle deck" )
  56         self.message2.grid( row = 2, columnspan = 2 )
  57 
  58         self.shuffle()
  59         self.grid()
  60 
  61     def shuffle( self ):
  62         """Shuffle the deck"""
  63 
  64         self.currentCard = 0
  65 
  66         for i in range( len( self.deck) ):
  67             j = random.randint( 0, 51 )
  68 
  69             #swap the cards
  70             self.deck[i],self.deck[j] = self.deck[j],self.deck[i]
  71 
  72         self.message1.config( text = "Deck is Shuffled" )
  73         self.message2.config( text = "" )
  74         self.dealButton.config( state = NORMAL )
  75 
  76     def dealCard( self ):
  77         """Deal one card from the deck"""
  78 
  79         #display the card, if it exists
  80         if self.currentCard < len( self.deck ):
  81             self.message1.config( text = self.deck[ self.currentCard ] )
  82             self.message2.config( text = "Card # %d" % self.currentCard )
  83         else:
  84             self.message1.config( text = "NO MORE CARDS TO DEAL" )
  85             self.message2.config( text = "Shuffle cards to continue" )
  86             self.dealButton.config( state = DISABLED )
  87 
  88         self.currentCard += 1   #increment card for next turn
  89 
  90 def main():
  91     Deck().mainloop()
  92 
  93 if __name__ == "__main__":
  94     main()

Chapter 11.1 ScrolledListBox used to select image

   1 #chapter11.1
   2 #ScrolledListBox used to select image.
   3 
   4 from Tkinter import *
   5 import Pmw
   6 
   7 class ImageSelection( Frame ):
   8     """List of available images and an area to display them"""
   9 
  10     def __init__( self, images ):
  11         """Create list of PhotoImages and Label to display them"""
  12 
  13         Frame.__init__( self )
  14         Pmw.initialise()
  15         self.pack( expand = YES, fill = BOTH )
  16         self.master.title( "Select an image" )
  17 
  18         self.photos = []
  19 
  20         #add PhotoImage object to list photos
  21         for item in images:
  22             self.photos.append( PhotoImage( file = item ) )
  23 
  24         #create scrolled list box with vertical scrollbar
  25         self.listBox = Pmw.ScrolledListBox( self, items = images,
  26                                             listbox_height = 3,
  27                                             vscrollmode = "static",
  28                                             selectioncommand = self.switchImage )
  29         self.listBox.pack( side = LEFT, expand = YES, fill = BOTH, padx = 5, pady = 5 )
  30 
  31         self.display = Label( self, image = self.photos[0] )
  32         self.display.pack( padx = 5, pady = 5 )
  33 
  34     def switchImage ( self ):
  35         """Change image in Label to current selection"""
  36 
  37         #get tuple containing index of selected list item
  38         chosenPicture = self.listBox.curselection()
  39 
  40         #configure label to display selected image
  41         if chosenPicture:
  42             choice = int( chosenPicture[0] )
  43             self.display.config( image = self.photos[ choice ] )
  44 
  45 def main():
  46     images = [ "c:\python23\logo.gif", "c:\python23\china.gif", "c:\python23\canada.gif", "c:\python23\logo.gif" ]
  47     ImageSelection(images).mainloop()
  48 
  49 if __name__ == "__main__":
  50     main()

Chapter 11.2 Copying selected text from one text area to another

   1 #chapter11.2
   2 #Copying selected text from one text area to another.
   3 
   4 from Tkinter import *
   5 import Pmw
   6 
   7 class CopyTextWindow( Frame ):
   8     """Demonatrate ScrolledText"""
   9 
  10     def __init__( self ):
  11         """Create two ScrolledText and a Button"""
  12 
  13         Frame.__init__( self )
  14         Pmw.initialise()
  15         self.pack( expand = YES, fill = BOTH )
  16         self.master.title( "ScrolledText Demo" )
  17 
  18         #create scrolled text box with word wrap enable
  19         self.text1 = Pmw.ScrolledText( self, text_width = 25, text_height = 12,
  20                                        text_wrap = WORD, hscrollmode = "static",
  21                                        vscrollmode = "static" )
  22         self.text1.pack( side = LEFT, expand = YES, fill = BOTH, padx = 5, pady = 5 )
  23 
  24         self.copyButton = Button( self, text = "Copy >>>", command = self.copyText )
  25         self.copyButton.pack( side = LEFT, padx = 5, pady = 5 )
  26 
  27         #create uneditable scrolled text box
  28         self.text2 = Pmw.ScrolledText( self, text_state = DISABLED, text_width = 25,
  29                                        text_height = 12, text_wrap = WORD,
  30                                        hscrollmode = "static", vscrollmode = "static" )
  31         self.text2.pack( side = LEFT, expand = YES, fill = BOTH, padx = 5, pady = 5 )
  32 
  33     def copyText( self ):
  34         """set the text in the second ScrolledText"""
  35 
  36         self.text2.settext( self.text1.get( SEL_FIRST,SEL_LAST ) )
  37 
  38 def main():
  39     CopyTextWindow().mainloop()
  40 
  41 if __name__ == "__main__":
  42     main()

Chapter 11.3 MenuBars with Balloons demonstration

   1 #chapter11.3
   2 #MenuBars with Balloons demonstration.
   3 
   4 from Tkinter import *
   5 import Pmw
   6 import sys
   7 
   8 class MenuBarDemo( Frame ):
   9     """Create window with a MenuBar"""
  10 
  11     def __init__( self ):
  12 
  13         Frame.__init__( self )
  14         Pmw.initialise()
  15         self.pack( expand = YES, fill = BOTH )
  16         self.master.title( "MenuBar Demo" )
  17         self.master.geometry( "500x200" )
  18 
  19         self.myBalloon = Pmw.Balloon( self )
  20         self.choices = Pmw.MenuBar( self, balloon = self.myBalloon )
  21         self.choices.pack( fill = X )
  22 
  23         #create File menu and items
  24         self.choices.addmenu( "File", "Exit" )
  25         self.choices.addmenuitem( "File", "command", command = self.closeDemo, label = "Exit" )
  26 
  27         #create Format menu and items
  28         self.choices.addmenu( "Format", "Change font/color" )
  29         self.choices.addcascademenu( "Format", "Color" )
  30         self.choices.addmenuitem( "Format", "separator" )
  31         self.choices.addcascademenu( "Format", "Font" )
  32 
  33         #add items to Format/Color menu
  34         colors = [ "Black", "Blue", "Red", "Green" ]
  35         self.selectedColor = StringVar()
  36         self.selectedColor.set( colors [0] )
  37 
  38         for item in colors:
  39             self.choices.addmenuitem( "Color", "radiobutton", label = item, command = self.changeColor,
  40                                       variable = self.selectedColor )
  41 
  42         #add items to Format/Font menu
  43         fonts = [ "Times", "Courier", "Helvetica" ]
  44         self.selectedFont = StringVar()
  45         self.selectedFont.set( fonts [0] )
  46 
  47         for item in fonts:
  48             self.choices.addmenuitem( "Font", "radiobutton", label = item, command = self.changeFont,
  49                                       variable = self.selectedFont )
  50 
  51         #add a horizontal separator in Font menu
  52         self.choices.addmenuitem( "Font", "separator" )
  53 
  54         #associate checkbutton menu item with BooleanVar object
  55         self.boldOn = BooleanVar()
  56         self.choices.addmenuitem( "Font", "checkbutton", label = "Bold", command = self.changeFont,
  57                                   variable = self.boldOn )
  58 
  59         #assoiate checkbutton menu item with BooleanVar object
  60         self.italicOn = BooleanVar()
  61         self.choices.addmenuitem( "Font", "checkbutton", label = "Italic", command = self.changeFont,
  62                                   variable = self.italicOn )
  63 
  64         #create canvas with text
  65         self.display = Canvas( self, bg = "white" )
  66         self.display.pack( expand = YES, fill = BOTH )
  67 
  68         self.sampleText = self.display.create_text ( 250, 100, text = "Sample Text", font = "Times 48" )
  69 
  70     def changeColor( self ):
  71         """change the color of the text on the Canvas"""
  72 
  73         self.display.itemconfig( self.sampleText, fill = self.selectedColor.get() )
  74 
  75     def changeFont( self ):
  76         """change the font of the text on the Canvas"""
  77 
  78         #get selected font and attach size
  79         newFont = self.selectedFont.get() + " 48"
  80 
  81         #determine which checkbutton menu items selected
  82         if self.boldOn.get():
  83             newFont += " bold"
  84 
  85         if self.italicOn.get():
  86             newFont += " italic"
  87 
  88         #configure sample text to be displayed in selected style
  89         self.display.itemconfig( self.sampleText, font = newFont )
  90 
  91     def closeDemo( self ):
  92         """Exit the program"""
  93 
  94         sys.exit()
  95 
  96 def main():
  97     MenuBarDemo().mainloop()
  98 
  99 if __name__ == "__main__":
 100     main()

Chapter 11.4 Popup menu demonstration

   1 #chapter11.4
   2 #Popup menu demonstration.
   3 
   4 from Tkinter import *
   5 
   6 class PopupMenuDemo( Frame ):
   7     """Demonstrate popup menus"""
   8 
   9     def __init__( self ):
  10         """create a Menu but do not add it to the Frame"""
  11 
  12         Frame.__init__( self )
  13         self.pack( expand = YES, fill = BOTH )
  14         self.master.title( "Popup Menu Demo" )
  15         self.master.geometry( "300x200" )
  16 
  17         #create and pack frame with initial white background
  18         self.frame1 = Frame( self, bg = "white" )
  19         self.frame1.pack( expand = YES, fill = BOTH )
  20 
  21         #create menu without packing it
  22         self.menu = Menu( self.frame1, tearoff = 0 )
  23 
  24         colors = [ "White", "Blue", "Yellow", "Red" ]
  25         self.selectedColor = StringVar()
  26         self.selectedColor.set( colors [0] )
  27 
  28         for item in colors:
  29             self.menu.add_radiobutton( label = item, variable = self.selectedColor,
  30                                        command = self.changeBackgroundColor )
  31 
  32         #Popup menu on right-mouse click
  33         self.frame1.bind( "<Button-3>", self.popUpMenu )
  34 
  35     def popUpMenu( self, event ):
  36         """Add the Menu to the Frame"""
  37 
  38         self.menu.post( event.x_root, event.y_root )
  39 
  40     def changeBackgroundColor( self ):
  41             """Change the Frame background color"""
  42 
  43             self.frame1.config( bg = self.selectedColor.get() )
  44 
  45 def main():
  46     PopupMenuDemo().mainloop()
  47 
  48 if __name__ == "__main__":
  49     main()

Chapter 11.5 Canvas paint program

   1 #chapter11.5
   2 #Canvas paint program.
   3 
   4 from Tkinter import *
   5 
   6 class PaintBox( Frame ):
   7     """Demonstrate drawing on a Canvas"""
   8 
   9     def __init__( self ):
  10         """Create Canvas and bind paint method to mouse dragging"""
  11 
  12         Frame.__init__( self )
  13         self.pack( expand = YES, fill = BOTH )
  14         self.master.title( "A simple paint program" )
  15         self.master.geometry( "300x150" )
  16 
  17         self.message = Label( self, text = "Drag the mouse to draw" )
  18         self.message.pack( side = BOTTOM )
  19 
  20         #create Canvas component
  21         self.myCanvas = Canvas( self )
  22         self.myCanvas.pack( expand = YES, fill = BOTH )
  23 
  24         #bind mouse dragging event to Canvas
  25         self.myCanvas.bind( "<B1-Motion>", self.paint )
  26 
  27     def paint( self, event ):
  28         """Create an oval of radius 4 around the mouse position"""
  29 
  30         x1,y1 = ( event.x - 4 ), ( event.y - 4 )
  31         x2,y2 = ( event.x + 4 ), ( event.y + 4 )
  32         self.myCanvas.create_oval( x1, y1, x2, y2 ,fill = "black" )
  33 
  34 def main():
  35     PaintBox().mainloop()
  36 
  37 if __name__ == "__main__":
  38     main()

Chapter 11.6 Scale used to control the size of a circle

   1 #chapter11.6
   2 #Scale used to control the size of a circle.
   3 
   4 from Tkinter import *
   5 
   6 class ScaleDemo( Frame ):
   7     """Demonstrate Canvas and Scale"""
   8 
   9     def __init__( self ):
  10         """Create Canvas with a circle controlled by a Scale"""
  11 
  12         Frame.__init__( self )
  13         self.pack( expand = YES, fill = BOTH )
  14         self.master.title( "Scale Demo" )
  15         self.master.geometry( "220x270" )
  16 
  17         #create Scale
  18         self.control = Scale( self, from_ = 0, to = 400, orient = HORIZONTAL,
  19                               command = self.updateCircle )
  20         self.control.pack( side = BOTTOM, fill = X )
  21         self.control.set( 10 )
  22 
  23         #create Canvas and draw circle
  24         self.display = Canvas( self, bg = "white" )
  25         self.display.pack( expand = YES, fill = BOTH )
  26 
  27     def updateCircle( self, scaleValue ):
  28         """Delete the circle, determine new size,draw again"""
  29 
  30         end = int( scaleValue ) + 10
  31         self.display.delete( "circle" )
  32         self.display.create_oval( 10, 10, end, end, fill = "red", tags = "circle" )
  33 
  34 def main():
  35     ScaleDemo().mainloop()
  36 
  37 if __name__ == "__main__":
  38     main()

Chapter 12.1 Simple exception handling example

   1 #chapter12.1
   2 #Simple exception handling example.
   3 
   4 number1 = raw_input( "Enter numerator:" )
   5 number2 = raw_input( "Enter denominator:" )
   6 
   7 #attempt to convert and divide values
   8 try:
   9     number1 = float( number1 )
  10     number2 = float( number2 )
  11     result = number1 / number2
  12 
  13 #float raises a ValueError exception
  14 except ValueError:
  15     print "You must enter two numbers"
  16 
  17 #division by zero raises a ZeroDivisionError exception
  18 except ZeroDivisionError:
  19     print "Attempted to divide by zero"
  20 
  21 #else clause's suite executes if try suite raises no exceptions
  22 else:
  23     print "%.3f / %.3f = %.3f" % ( number1, number2, result )

Chapter 12.2 Demonstrating a programer-defined exception class

   1 #chapter12.2
   2 #Demonstrating a programer-defined exception class.
   3 
   4 import math
   5 
   6 class NegativeNumberError( ArithmeticError ):
   7     """Attempted improper operation on negative number"""
   8     pass
   9 
  10 def squareRoot( number ):
  11     """Computes square root of number not permitted. if  number is less than 0."""
  12 
  13     if number < 0:
  14         raise NegativeNumberError, "Square root of negative number not permitted"
  15 
  16     return math.sqrt( number )
  17 
  18 while 1:
  19 
  20     #get user-entered number and compute square root
  21     try:
  22         userValue = float( raw_input( "\nPlease enter a number:" ) )
  23         print squareRoot( userValue )
  24 
  25     #float raises ValueError if input is not numerical
  26     except ValueError:
  27         print "The entered value is not a number"
  28 
  29     #squareRoot raises NegativeNumberError if number is negative
  30     except NegativeNumberError, exception:
  31         print exception
  32 
  33     #successful excution: terminate while loop
  34     else:
  35         break

Chapter 13.1 Searching string for a substring

   1 #chapter13.1
   2 #Searching string for a substring.
   3 
   4 #counting the occurrences of a substring.
   5 string1 = "Test1, Test2, Test3, Test4, Test5, Test6"
   6 
   7 print '"test" occurs %d times in \n\t%s' % ( string1.count( "test" ), string1 )
   8 print '"test" occurs %d times after 18th character in  \n\t%s' % \
      ( string1.count( "test", 18, len( string1 ) ), string1 )
   9 print
  10 
  11 #finding a substring in a string
  12 string2 = "Odd or even"
  13 
  14 print '"%s" contains "or" starting at index %d' % ( string2, string2.find( "or" ) )
  15 
  16 #find index of "even"
  17 try:
  18     print '"even" index is', string2.index( "even" )
  19 except ValueError:
  20     print '"even" does not occur in "%s"' % string2
  21 
  22 if string2.startswith( "Odd" ):
  23     print '"%s" starts with "Odd"' % string2
  24 
  25 if string2.endswith( "even" ):
  26     print '"%s" ends with "even"\n' % string2
  27 
  28 #searching from end of string
  29 print 'Index from end of "test" in "%s" is %d' % ( string1, string1.rfind( "test" ) )
  30 print
  31 
  32 #find rindex of "Test"
  33 try:
  34     print 'First occurrence of "Test" from end at index', string1.rindex( "Test" )
  35 except ValueError:
  36     print '"Test" does not occur in "%s"' % string1
  37 
  38 print
  39 
  40 #replacing a substring
  41 string3 = "One, one, one, one, one, one"
  42 
  43 print "Original:", string3
  44 print 'Replaced:", "one" with "two":', string3.replace( "one", "two" )
  45 print "Replaced 3 maximum:", string3.replace( "one", "two", 3 )

Chapter 13.2 Simple regular-expression example