" I think the very concept of an elite commission deciding for the American people who deserves to be heard is profoundly wrong." --former Congressman Newt Gingrich on the "Commission on Presidential Debates"
|A guide to writing event-driven GUI applications in Perl using the Tk module. |
|Wirtten by ELJONTO\Cyb3r_Shad0w (Both are me). |
________________________________________________________________________________
Contents:
-Introduction
-Notes on global/local variables
-Mainwindow/widget and argument syntax
-Geometry managers
-Structure of a Perl Tk program
-Common widgets and widget arguments
-Configuring widgets
-Example of a perl Tk application
-Anatomy of example application
-Example programs using different widgets
-Label, Entry Fields, Buttons and Text-Areas
-Dropdown boxes
-Listbox
-Scrollbars embedded within Text-Areas
-Menus
-Using multiple windows (Toplevels)
-Outro
INTRODUCTION:
People always assume perl to be a simple scripting language with basic acess to web scripting, however this is not so. Perl is so much more, and with the use of user-written modules can have amazing capabilities on a variety of topics.
In this article i'll show you how to make use of the Perl::Tk module to create event-orientated GUI applications.
NOTES ON GLOBAL AND LOCAL VARIABLES:
Before we begin, you'll notice most variables have 'my' in front of them. This is to make the variables 'local'. This means that if a variable has 'my' in front of it, it will only be able to be used in the function that it's in. This means that you can use many variables with the same names in different functions as long as you declare them to be 'local'. In perl, it is not an error to redeclare a variable, so make sure you know whether you want variables to be 'local' or 'global'. Global means the variable can be acessed and used by all functions. To make a variable 'global' just omit the 'my' in front of it.
MAINWINDOW/WIDGET AND ARGUMENT SYNTAX:
Good, now with that out the way we can begin.
To make your main window, you need to assign it a variable so that it can incorporate widgets (Things like labels, buttons etc). And all widgets need to be assigned to a variable so that you can access them.
To make a new mainwindow and assign it to a variable you follow this syntax:
CODE :
$mainwindow=new MainWindow();
To make a new widget and assign it to a variable you folow this syntax:
CODE :
widgets can take as many arguments as they can allow, and arguments follow this syntax and are separated by commas:
CODE :
-argument=>value,
There are many, many widgets available so in this article i'll only cover a few most commonly used ones.
GEOMETRY MANAGERS:
Geometry managers are how your Mainwindow is formatted to accommodate all of your widgets.
The four types of most commonly-used geometry managers are: pack(), grid(), place() and form().
pack(): A geometry manager to pack widgets into a window by filling the widget in certain positions in a certain order or in order of declaration.
grid(): A geometry manager to arrange all of your widgets into an imaginary 'grid'. so all you widgets are positioned in a cell according to a row/column.
place():A geometry manager to situate widgets at given x,y co-ordinates.
form(): A geometry manager that combines use of pack() and place() to create a very powerful method of arranging your Tk window.
I almost always use grid(), simply because it's very simple to learn and accommodate for all uses and very powerful for simple or advanced applications. However if you are creating a large-scale perl Tk GUI app (unlikely) you should probably use place() or form(). For smaller apps pack() or grid() are just fine. Because this is a beginners guide- I will only show you the use of grid().The basic arguments for grid include:
-row=>x,
-column=>x,
-rowspan=>x, (how many rows should accommodate widget)
-columnspan=>x, (how many columns should accommodate widget)
-sticky=>x, (used to stick to the side of the cell the widget is postioned in, the value can be 'n','s','e','w','ne','nw','ns','se','sw','ew'. For 'ns' and 'ew' it will stretch the widget in that direction to fit the cell).
There are more arguments, which you can read up about, but those are the only neccessary basics.
STRUCTURE OF A PERL TK PROGRAM:
All perl Tk applications are structured as follows:
CODE :
GUI building code
MainLoop;
functions and subroutines
All perl Tk applications MUST have a 'MainLoop', otherwise they won't work. MainLoop; separates the GUI building code from the subroutines and functions that get called by user-interaction with the widgets when run. Above MainLoop; you write all GUI building code, the mainwindows, the frames, the widgets. Below the MainLoop; you have all functions and subroutines that get called by user-interaction.
COMMON WIDGETS AND WIDGET ARGUMENTS:
Below are a few of the most commonly used widgets in GUI applications, please note that capitaliasation is important:
Label() -display some text
Button() -display a button (duh)
Entry() -display a field to enter text
Text() -display a textarea
Menu() -configure a menu for you application
Optionmenu() -display a drop-down box of options
ProgressBar() -display a graphical aid of progress completed (loading bar etc)
getOpenFile() -displays the default navigation window to a location and file to open
getSaveFile() -displays the default navigation window to a location and file to save
Scrollbar() -displays a scroll bar to be embedded into a text-area or other compatible widget
Below are some arguments that can be used with most widgets:
-bg=>'x', or -background=>x, Can take arguments as 'black' or '#000000' etc
-fg=>x, or -foreground=>x, Same follows as background
-activebackground=>'x', or '#000000' etc. Colour of background when cursor is hovering over it.
-activeforegroud=>'x', or '#000000' etc. Colour of foreground when cursor is hovering over it.
-text=>"x",
-width=>x,
-height=>x,
-command=>\&subfunction, or -command=>sub{statements;},
-variable=>\$var,
CONFIGURING WIDGETS:
Once widgets have been initialised, you can change or configure the widget without having to create it again. You do this as follows:
CODE :
$widgetvar->configure(re-declare arguments you want to change);
Some widgets allow the program to enter information as well as the user, widgets such as a textarea or an entry field. This is done as follows:
CODE :
$widgetvar->insert('postion',"to insert");
The position can be numerical- 1.0 for the beginning etc, or text- 'end' etc.
EXAMPLE OF A PERL TK APPLICATION:
Ok, here I will show you how to use what you know and create a basic perl tk application. This following example will show you how make a window, add basic widgets, and collected widget data with the use of get() inside of a subroutine.
CODE :
use Tk;
my $mw=new MainWindow();
my $frm=$mw->Frame()->grid();
my $label=$frm->Label(-text=>"Enter your name:")->grid(-row=>0,-column=>0,-sticky=>'w');
my $entrybox=$frm->Entry()->grid(-row=>0,-column=>1);
my $gobutton=$frm->Button(-text=>"go",-command=>\&function1)->grid(-row=>0,-column=>2,-sticky=>'e');
my $textarea=$frm->Text(-width=>30,-height=>5)->grid(-row=>2,-column=>0,-columnspan=>3);
MainLoop;
sub function1{
my $name=$entrybox->get();
$textarea->insert('end',"Hello $name\n");
}
ANATOMY OF EXAMPLE APPLICATION:
line 1: Tells compiler that we need to use the Tk module.
line 2: Creates a new Tk window and binds it to a variable.
line 3: Creates a new frame to hold widgets and stores the frame inside our new window.
line 4: Creates a label to dislay text, places it to grid co-ords and places the label inside of our frame.
line 5: Creates an entry field to input text, places it to grid co-ords and places the entry inside of our frame.
line 6: Creates a button to display text and initiate our subroutine, places it to grid co-ords and places the button inside of our frame.
line 7: Creates a text-area to dislay text given to it, places it to grid co-ords and places the text area inside of our frame.
line 8: Signifies GUI base-building code complete.
line 9: Creates subroutine "function1".
line 10:Uses get() to collect data from entrybox and saves it into variable $name.
line 11:Inserts "helo $name" into our text-area widget.
line 12:Ends subroutine "function1".
EXAMPLE PROGRAMS USING DIFFERENT WIDGETS:
Here are a few very short programs making use of some of the widgets we've talked about.
==Label, Entry Fields, Buttons and Text-Areas:
See "Example of a perl Tk application" above.
==Dropdown boxes:
CODE :
use Tk;
my $mw=new MainWindow;
my $frm=$mw->Frame()->grid();
my $lab=$frm->Label(-text=>"Choose option:")->grid(-row=>0,-column=>0);
my $dropdownbox=$frm->Optionmenu(-options=>["Male", "Female"],-variable=>\$var)->grid(-row=>1,-column=>0);
my $txt=$frm->Text(-width=>20,-height=>10)->grid(-row=>2,-column=>0);
my $button=$frm->Button(-text=>"Go",-command=>\&maleorfemale)->grid(-row=>3,-column=>0);
MainLoop;
sub maleorfemale {
if($var eq 'Male'){$txt->insert('end',"You are Male")}else{$txt->insert('end',"You are female")}
}
==Listbox:
CODE :
use Tk;
my $mw=new MainWindow();
my $frm=$mw->Frame()->grid();
my $lab=$frm->Label(-text=>"Gender:")->grid(-row=>0,-column=>0);
my $lst=$frm->Listbox(-selectmode=>'single',-width=>30,-height=>5)->grid(-row=>1,-column=>0);
my $but=$frm->Button(-text=>"Go",-command=>\&button_push)->grid(-row=>2,-column=>0);
my $txt=$frm->Text(-width=>30,-height=>5)->grid(-row=>3,-column=>0);
$lst->insert('end',"Male");
$lst->insert('end',"Female");
MainLoop;
sub button_push{
my $selected=$lst->curselection();
my $gender=$lst->get($selected);
$txt->insert('end',"You selected $gender.\n");
}
==Scrollbars embedded within Text-Areas:
CODE :
use Tk;
my $mw=new MainWindow;
my $frm=$mw->Frame()->grid();
my $txt=$frm->Text(-wrap=>'none',-width=>40,-height=>10)->grid(-row=>0,-column=>0);
my $srl_y=$frm->Scrollbar(-orient=>'v',-command=>[yview => $txt])->grid(-row=>0,-column=>1,-sticky=>"ns");
my $srl_x=$frm->Scrollbar(-orient=>'h',-command=>[xview => $txt])->grid(-row=>1,-column=>0,-sticky=>"ew");
$txt -> configure(-yscrollcommand=>['set', $srl_y],-xscrollcommand=>['set',$srl_x]);
my $mw=new MainWindow();
my $frm=$mw->Frame()->grid();
my $but=$frm->Button(-text=>">>Click to open a toplevel window<<",-command=>\&toplevel)->grid(-row=>1,-column=>0);
MainLoop;
sub toplevel{
my $toplevel=new MainWindow();
my $toplevelfrm=$toplevel->Frame()->grid();
my $lab=$toplevelfrm->Label(-text=>"A Toplevel window!")->grid(-row=>1,-column=>0);
MainLoop;
}
OUTRO:
Well, that's it- Hope you enjoyed this beginners guide, I might write later articles covering slightly more complex areas of Perl Tk programming
-ELJONTO || Cyb3r_Shad0w
Cast your vote on this article 10 - Highest, 1 - Lowest
Comments: Published: 13 comments.
HackThisSite is the collective work of the HackThisSite staff, licensed under a CC BY-NC license.
We ask that you inform us upon sharing or distributing.