Perl_21_GraphicsTk

Shared by: luckbbs
Categories
Tags
-
Stats
views:
0
posted:
2/9/2012
language:
pages:
30
Document Sample
scope of work template
							                          Chapter 21 – Graphics/Tk
        Outline
        21.1           Introduction
        21.2           GD Module: Creating Simple Shapes
        21.3           GD Module: Image Manipulation
        21.4           Chart Module
        21.5           Introduction to GUI
        21.6           Introduction to Tk
        21.7           Tk: GUI Components
        21.8           Tk Case Study: A GUI Application




 2001 Prentice Hall, Inc. All rights reserved.
                                              21.1 Introduction

      • Graphics
              – Video games, billboards, movies
              – Web pages
                     • Pictures used to provide information
              – Graphics are not just pictures
                     • Colors, lines, patterns
      • Graphics in Perl
              – No graphics functions built-in
              – Graphics modules allow graphic manipulation




 2001 Prentice Hall, Inc. All rights reserved.
              21.2 GD Module: Creating Simple Shapes

      • The GD module
              – Used to create and manipulate images
              – Like a paint program
                     • Done through text commands
                     • User does not draw directly




 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                           Outline
2    # Fig 21.1: fig21_01.pl
3    # Using the GD module to create shapes.
                                                                                    fig21_01.pl
4
5    use strict;
6    use warnings;
7    use GD;
8
9    my $image = new GD::Image( 320, 320 );
10
11   my   $white = $image->colorAllocate( 255, 255, 255 );
12   my   $red = $image->colorAllocate( 255, 0, 0 );
13   my   $green = $image->colorAllocate( 0, 255, 0 );                 Creates the colors of
14   my   $blue = $image->colorAllocate( 0, 0, 255 );
                                                                       the variable’s name
15   my   $black = $image->colorAllocate( 0, 0, 0 );
16   my   $purple = $image->colorAllocate( 255, 0, 255 );
17
18   $image->filledRectangle( 15, 15, 150, 150, $red );
19   $image->arc( 200, 200, 50, 50, 0, 360, $black );
                                                                          Creates a red square
20   $image->fill( 200, 200, $blue );                              Creates a black circle and fills it blue
21   $image->rectangle( 100, 100, 200, 125, $green );
22   $image->fillToBorder( 150, 110, $green, $green );             Creates a green rectangle
23
24   my $polygon = new GD::Polygon();
25   $polygon->addPt( 20, 300 );
26   $polygon->addPt( 20, 175 );                  Creates a shape using
27   $polygon->addPt( 100, 175 );                 the given points
28
 2001 Prentice Hall, Inc. All rights reserved.
29   $image->polygon( $polygon, $blue );                                                  Outline
30   $image->fill( 50, 200, $purple );
31
                                                  Fills the polygon purple and      fig21_01.pl
32   $polygon->setPt( 0, 30, 300 );
                                                  makes it outlined in blue
33   $polygon->setPt( 1, 110, 300 );
34   $polygon->setPt( 2, 110, 175 );
35
36   $image->filledPolygon( $polygon, $black );               Creates another polygon
37                                                            and fills it black
38   open( PICT, ">fig21_02.png" ) or                      Stores the picture to a file
39      die( "Can not open picture: $!" );
40
41   binmode( PICT );
42   print( PICT $image->png() );




 2001 Prentice Hall, Inc. All rights reserved.
            21.2 GD Module: Creating Simple Shapes




        Fig. 21.2 Contents of fig21_02.png.


 2001 Prentice Hall, Inc. All rights reserved.
                 21.3 GD Module: Image Manipulation

      • More of the GD module
              – Image manipulation




 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                 Outline
2    # Fig 21.3: fig21_03.pl
3    # A program to enlarge a picture.                                      fig21_03.pl
4
5    use GD;
6    use strict;
7    use warnings;
8
9    my $image = GD::Image->newFromPng( "fig21_02.png" );          Creates a new image
10 my @dimensions = $image->getBounds();                           from a .png file
11 my @newDimensions = map( { $_ * 2 } @dimensions );
12
                                                                           Copies $image from
13 my $newImage = new GD::Image ( @newDimensions );
                                                                           point (0, 0) with
                                                                           specifications in
14 $newImage->copyResized( $image, 0, 0, 0, 0, @newDimensions,
                                                                           @dimensions and
15      @dimensions );
                                                                           creates a new image
16                                                                         starting at (0, 0) with the
17 open( FILE, ">fig21_04.png" ) or                                        @newDimensions
18      die( "Could not write to file: $!" );
19
20 binmode( FILE );
21 print( FILE $newImage->png() );                Stores the new image in a file
22
23 close( FILE ) or die( "Can not close file: $!" );

 2001 Prentice Hall, Inc. All rights reserved.
                 21.3 GD Module: Image Manipulation




                                                  Fig. 21.4 Contents of fig21_04.png.


 2001 Prentice Hall, Inc. All rights reserved.
                                         21.4 Chart Module

      • The Chart module
              – Used to create custom charts and graphs
              – Extended modules
                     • Chart::Lines
                     • Chart::Bars
                     • Chart::Points




 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                               Outline
2    # Fig 21.5: fig21_05.pl
3    # Using the Chart module.
                                                                                         fig21_05.pl
4
5    use strict;
6    use warnings;
7    use Chart::Lines;
                                                  Uses the Chart::Lines module
8
9    my $line = new Chart::Lines();
10 my $file = "fig21_06.png";
11 my @labels = ( "first", "second" );
                                                                      Sets up the basics for the graph;
12 my %colors = ( "dataset0" => [ 100, 100, 255 ],
13      "dataset1" => [ 255, 100, 100 ],
                                                                      title, x label, y label, colors
14      "background" => [ 150, 235, 200 ] );
15
16 $line->set( "title" => "Test Chart", "x_label" => "letter" );
17 $line->set( "y_label" => "number", "legend" => "left" );
18 $line->set( "legend_labels" => \@labels, "colors" => \%colors
); $line->set( "grey_background" => 0 );
19
20
21 my @Xlabels = ( 'a', 'b', 'c', 'd' );
22 my @dataset1 = ( 1, 2, 3, 4 );                                  Sets up the value for the x label, as well
23 my @dataset2 = ( 2, 3, 5, 9 );                                  as the data to be entered into the graph
24
25 my @data = ( \@Xlabels, \@dataset1, \@dataset2 );
26
27 $line->png( $file, \@data );
 2001 Prentice Hall, Inc. All rights reserved.
                                         21.4 Chart Module




        Fig. 21.6 Contents of fig21_06.png.


 2001 Prentice Hall, Inc. All rights reserved.
                                  21.5 Introduction to GUI

      • Tk
              – A GUI toolkit
              – Use the Tk module
      • GUI
              – Graphical User Interface
              – Gives a program a distinctive look and feel
              – Built with GUI components
                     • Object in which the user interacts with mouse or keyboard




 2001 Prentice Hall, Inc. All rights reserved.
                                    21.6 Introduction to Tk

      • Event-handler loop
              – Loop in which program waits for user interaction (an event)
                     • Mouse click, key stroke, or any other wide variety
                     • MainLoop()
              – When an event occurs the loop invokes a function as
                specified to handle the event
      • Window
              – The main Tk object
              – Other objects placed in the window
              – Example: A Web browser




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                               Outline
 2   # Fig 21.7: fig21_07.pl
 3   # A simple Perl/Tk program.
 4                                                                                        fig21_07.pl
 5   use warnings;
 6   use strict;
 7   use Tk;
 8
 9   my $main = new MainWindow();                   Create a new window
10
11   my $label = $main->Label();                    Create a label
12   my $button = $main->Button();                  Create a button
13
14   $label->configure( -text => 'Look at me!' );
15   $button->configure( -text => 'Exit', -command => \&destroy );
16
17   $label->pack();
18   $button->pack();                                               Sets the text properties of both
                                       Place the GUI components on the window
19                                                                  the label and the button as well
20   MainLoop();                                                    as the command of the button
21                                     Calls the MainLoop
22   sub destroy                       function to wait for an event
23   {                                 to occur
24      $main->destroy();
25   }



          label                                             button


 2001 Prentice Hall, Inc. All rights reserved.
                                21.7 Tk: GUI Components

      • Listbox
              – Displays a list of items which the user can select from
      • RadioButton
              – Offers choices
              – Only one radio button can be selected at a time
      • Scale
              – A vertical or horizontal slider
              – Its value can be set by dragging it to the appropriate location




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                               Outline
 2   # Fig 21.8: fig21_08.pl
 3   # Perl/Tk program using GUI components.
 4                                                                                       fig21_08.pl
 5   use strict;
 6   use warnings;
 7   use Tk;
 8
                                                  Defines an array of strings that
 9   our $main = new MainWindow();
10
                                                  will be placed into a list box
11   my @animals =
12      qw( aardvark baboon cheetah dog elephant yak zebu );
13
14   $main->Label( -text => "Select an animal:" )->pack();                           Creates a label that asks the
15   my $list = $main->Listbox();                                                    user to select an animal
16   $list->insert( 'end', @animals );
17   $list->bind( '<Double-1>' => \&choose1 );
18   $list->pack();                                   Creates              a new list box and
19                                                                inserts the items from the array
20   MainLoop();
21
22   sub choose1
23   {
24      my $animal = $list->get( $list->curselection() );                            Gets the current
25      my $color;                                                                   selection from the list
26      my $window = $main->Toplevel();         Creates a new
27                                                         top level window
28      $window->Label( -text => "Select a color:" )->pack();
29      my @colors = qw( grey brown black tan );
30
 2001 Prentice Hall, Inc. All rights reserved.
31       foreach ( @colors ) {                                                        Outline
32          $window->Radiobutton( -text => $_,
33             -variable => \$color, -value => $_ )->pack();           Creates radio buttons
34       }
                                                                             fig21_08.pl
                                                                       for each of the colors
35                                                                     in the array
36       $window->Button( -text => 'Choose', -command =>
37          [ \&choose2, $animal, \$color, $window ] )->pack();
                                                                       Creates a button to
38   }
39
                                                                       choose the desired color
40   sub choose2
41   {
42      my ( $animal, $color, $parent ) = @_;
43      my $value = 0;
44      $color = $$color;
45      my $window = $parent->Toplevel();         Creates another top level window
46
47       $window->Scale( '-orient' => 'horizontal',               Creates a new scale that runs
48          '-from' => 0, '-to' => 100, '-tickinterval' => 20,    horizontal across the window
49          '-label' =>
50             'Select a size in feet:', '-length' => 200,
51             -showvalue => 1,
52          '-variable' => \$value, )->pack();
53                                                                Creates another button to
54       $window->Button( -text => 'Choose',                      choose the current scale setting
55          -command =>
56             [ \&choose3, $animal, $color, \$value, $window ], )->
57             pack();
58   }
59
 2001 Prentice Hall, Inc. All rights reserved.
60   sub choose3                                                                    Outline
61   {
                                                             Creates the last window
62      my ( $animal, $color, $value, $parent ) = @_;
                                                             of the program fig21_08.pl
63      my $window = $parent->Toplevel();
64
65       $window->Label( -text => "Your animal is a $animal." )->
66          pack();
67       $window->Label( -text => "It's color is $color." )->pack();
68       $window->Label( -text =>
69          "It's size is $$value feet tall." )->pack();      Creates labels to show the output
70                                                             based on what the user selected
71       $window->Button( -text => 'Done',
72          -command => \&destroy )->pack();
73   }                                            This button is used to
74                                                terminate the program
75   sub destroy
76   {
77      $main->destroy()
78   }




 2001 Prentice Hall, Inc. All rights reserved.
                                21.7 Tk: GUI Components




                                                  listbox




        Fig. 21.9 Fig21_08.pl’s main window.


 2001 Prentice Hall, Inc. All rights reserved.
                                21.7 Tk: GUI Components




                                                           radio buttons




        Fig. 21.10 Fig21_08.pl’s first top-level window.


 2001 Prentice Hall, Inc. All rights reserved.
                                21.7 Tk: GUI Components




                                                  scale




        Fig. 21.11 Fig21_08.pl’s third window.


 2001 Prentice Hall, Inc. All rights reserved.
                                21.7 Tk: GUI Components




        Fig. 21.12 Fig21_08.pl’s final window.


 2001 Prentice Hall, Inc. All rights reserved.
              21.8 Tk Case Study: A GUI Application

      • Frames
              – Used to group similar components
              – Can help add to organization of the window




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                 Outline
 2   # Fig 21.13: fig21_13.pl
 3   # GUI Calculator with Tk.
 4
                                                                           fig21_13.pl
 5   use strict;
 6   use warnings;
 7   use Tk;
 8
 9   my $calculator = new MainWindow();        Creates the window
10   our ( $number1, $number2 );               for the program
11   my $oldOperator = '';
12   our $label = $calculator->Label( width => '21' )->pack();      This label is used to output
13
                                                                    the calculation to the user
14   my @frames;
15
                                                     Creates three frames on the
16   for ( 1 .. 3 ) {
                                                     window   used to organize it better
17      push( @frames,
18         $calculator->Frame()->pack( -side => 'top' ) );
19   }
20
21   my $frame4 = $calculator->Frame()->pack( -side => 'top' );
22   my $frame5 = $calculator->Frame()->pack( -side => 'top' );
23
24   for ( 1 .. 9 ) {
25      my $frame = $frames[ int( ( $_ - 1 ) / 3 ) ];
26      $frame->Button( text => $_,                         Creates   the nine number buttons
27         command => [ \&number, $_ ] )->pack( -side => "left" );
28   }
29
 2001 Prentice Hall, Inc. All rights reserved.
30   $frame4->Button( text => 'Enter',                                       Outline
31      command => [ \&calculate, '=' ] )->pack( -side => "left");
32
33   $frame4->Button( text => '0',                                     fig21_13.pl
34      command => [ \&number, 0 ] )->pack( -side => "left" );
35
36   $frame4->Button( text => 'Clear',
37      command => [ \&calculate, 'cl' ] )->pack( -side => "left" );
38
39   $frame5->Button( text => '+',
40      command => [ \&calculate, '+' ] )->pack( -side => "left" );
41
42   $frame5->Button( text => '-',
43      command => [ \&calculate, '-' ] )->pack( -side => "left" );
44
45   $frame5->Button( text => '*',
46      command => [ \&calculate, '*' ] )->pack( -side => "left" );
47
48   $frame5->Button( text => '/',
49      command => [ \&calculate, '/' ] )->pack( -side => "left" );
50
51   MainLoop();
52
53   sub number
54   {
55      my $digit = shift();
56      $number1 = $number1 ? $number1 . $digit : $digit;
57      $label->configure( text => $number1 );
58
59       if ( $oldOperator eq '=' ) {
60          $number2 = 0;
61       }
62   }
 2001 Prentice Hall, Inc. All rights reserved.
63                                                                                   Outline
64 sub calculate
65 {
66     my $operation = shift();                                                  fig21_13.pl
67
68     if ( $operation eq 'cl' ) {
69         clear();
70         $label->configure( text => $number1 );
71     }
72     elsif ( $operation eq '=' ) {
73
74         if ( $oldOperator ) {
75
76              if ( $oldOperator eq '/' && ( $number1 == 0 ) ) {
77                   $label->configure(
78                        text => 'Error: Divide by zero.' );
79                   clear();
80              }
81              else {
82                                                        Performs the correct
83                   if ( $oldOperator eq '+' ) {         mathematical operation based
84                        $number2 += $number1;           on the button the user pressed
85                   }
86                   elsif ( $oldOperator eq '-' ) {
87                        $number2 -= $number1;
88                   }
89                   elsif ( $oldOperator eq '*' ) {
90                        $number2 *= $number1;
91                   }
92                   elsif ( $oldOperator eq '/' ) {
93                        $number2 /= $number1;
94                   }
95
 2001 Prentice Hall, Inc. All rights reserved.
96                   $number1 = 0;                                            Outline
97                   $oldOperator = $operation;
98                   $label->configure( text => $number2 );
99              }                                                       fig21_13.pl
100        }
101        else {
102             $number2 = $number1;
103             $number1 = 0;
104             $oldOperator = $operation;
105        }
106    }
107    elsif ( $oldOperator ) {
108
109        if ( ( $oldOperator eq '/' ) && ( $number1 == 0 ) ) {
110             $label->configure( text => 'Error: Divide by zero' );
111             clear();
112        }
113        else {
114
115             if ( $oldOperator eq '+' ) {
116                  $number2 += $number1;
117             }
118             elsif ( $oldOperator eq '-' ) {
119                  $number2 -= $number1;
120             }
121             elsif ( $oldOperator eq '*' ) {
122                  $number2 *= $number1;
123             }
124             elsif ( $oldOperator eq '/' ) {
125                  $number2 /= $number1;
126             }
 2001 Prentice Hall, Inc. All rights reserved.
127           elsif ( $oldOperator eq '=' ) {                Outline
128              $number2 = $number1 || $number2;
129           }
130                                                    fig21_13.pl
131           $number1 = 0;
132           $oldOperator = $operation;
133           $label->configure( text => $number2 );
134       }
135    }
136    else {
137       $number2 = $number1;
138       $number1 = 0;
139       $oldOperator = $operation;
140    }
141 }
142
143 sub clear
144 {
145    $number2 = 0;
146    $number1 = 0;
147    $oldOperator = "";
148 }




 2001 Prentice Hall, Inc. All rights reserved.
                                                         Outline

                                                  fig21_13.pl
                                                  Program Output




 2001 Prentice Hall, Inc. All rights reserved.

						
Related docs
Other docs by luckbbs
Perl_13_References
Views: 0  |  Downloads: 0
Perl_11_File and Directory Manipulation
Views: 0  |  Downloads: 0
How_to_Write_Better_Test_Cases
Views: 10  |  Downloads: 0
Perl_24_HTML_1
Views: 0  |  Downloads: 0
ajax_rails
Views: 0  |  Downloads: 0
Perl_04_Arrays and Hashes
Views: 1  |  Downloads: 0
Perl_20_Data Structures
Views: 0  |  Downloads: 0
yapache_oscon2006
Views: 2  |  Downloads: 0
Perl_14_Objects and Modules
Views: 1  |  Downloads: 0