You are on page 1of 48

Perl/TkTutorialCreateGUIwithPerl'sTkModule

Introduction

.........................................................................................................................................................................

2
Applications

...................................................................................................................................................................

2
Philosophy

......................................................................................................................................................................

2
Perl/TkRequirements

.....................................................................................................................................................

3
Installing/UsingPerl

.......................................................................................................................................................

3
HelloWorld

.........................................................................................................................................................................

3
Widgets1:Button,Entry,Label

........................................................................................................................................

5
Button

.............................................................................................................................................................................

6
Entry

...............................................................................................................................................................................

6
Label

...............................................................................................................................................................................

7
Widgets2:Frame,Text,Scrollbar,Scale

...........................................................................................................................

8
Frame

.............................................................................................................................................................................

8
Text

.................................................................................................................................................................................

8
Scrollbar

.........................................................................................................................................................................

9
Scale

.............................................................................................................................................................................

11
Dialogs

..............................................................................................................................................................................

12
messageBox

..................................................................................................................................................................

12
chooseColor

..................................................................................................................................................................

13
getOpenFile

..................................................................................................................................................................

13
Toplevel

........................................................................................................................................................................

14
Widgets3:Radiobutton,Checkbutton

.............................................................................................................................

15
Radiobutton

..................................................................................................................................................................

15
Checkbutton

..................................................................................................................................................................

16
Widgets4:Listbox

...........................................................................................................................................................

18
Listbox

..........................................................................................................................................................................

18
Widgets5:Menubutton,Menu,Optionmenu

..................................................................................................................

20
Menubutton

..................................................................................................................................................................

20
Menu

.............................................................................................................................................................................

21
Optionmenu

.................................................................................................................................................................

23
SomemoreWidgetsCanvas,Message,Adjuster,Scrolled

............................................................................................

24
Canvas

..........................................................................................................................................................................

24
Message

........................................................................................................................................................................

24
Adjuster

........................................................................................................................................................................

24
Scrolled

........................................................................................................................................................................

25
GeometryManagement:Grid,Pack

................................................................................................................................

26
grid

...............................................................................................................................................................................

26
pack

.............................................................................................................................................................................

27
SomeCommonWidgetOptions

.......................................................................................................................................

28
SomeTkCommands

.........................................................................................................................................................

29
Bind

..............................................................................................................................................................................

29
NowWhat?

........................................................................................................................................................................

31
Reference

...........................................................................................................................................................................

31
Books

...........................................................................................................................................................................

31
Manual

..........................................................................................................................................................................

31
ExternalSites

................................................................................................................................................................

31
Appendix

...........................................................................................................................................................................

31
AppendixA:AbouttheAuthor

...................................................................................................................................

31
AppendixB:CommonlyMademistakesinPerl/Tk

...................................................................................................

32
AppendixC:Tcl/TkAndPerl/Tk

................................................................................................................................

32

AppendixD:Codes

.....................................................................................................................................................

32
AppendixE:FeedBacks

..............................................................................................................................................

33
AppendixF:Comments

..............................................................................................................................................

33
Index

........................................................................................................................................................................

33
Introduction

.............................................................................................................................................................

33
HelloWorld

.............................................................................................................................................................

36
Widget1

..................................................................................................................................................................

38
Widget2

..................................................................................................................................................................

40
Widget5

..................................................................................................................................................................

43
Widget6

..................................................................................................................................................................

44
GeometryManagement

...........................................................................................................................................

44
NowWhat?

..............................................................................................................................................................

46
Appendix

.................................................................................................................................................................

48

Introduction
Perl/Tk(alsoknownaspTk)isacollectionofmodulesandcodethatattemptstowedtheeasily
configuredTk8widgettoolkittothepowerfullexigraphic,dynamicmemory,I/O,andobjectoriented
capabilitiesofPerl5Inotherwords,itisaninterpretedscriptinglanguageformakingwidgetsand
programswithGraphicalUserInterfaces(GUI)
PerlorPracticalExtractionandReportLanguageisdescribedbyLarryWall,Perl'sauthor,asfollows:
"Perlisaninterpretedlanguageoptimizedforscanningarbitrarytextfiles,extractinginformationfromthosetextfiles,
andprintingreportsbasedonthatinformationIt'salsoagoodlanguageforanysystemmanagementtasksThe
languageisintendedtobepractical(easytouse,efficient,complete)ratherthanbeautiful(tiny,elegant,minimal)"
Theperlintromanpagehasthistosay
Perlisageneralpurposeprogramminglanguageoriginallydevelopedfortextmanipulationandnowused
forawiderangeoftasksincludingsystemadministration,webdevelopment,networkprogramming,GUI
development,andmore
Tk,theextension(ormodule)thatmakesGUIprogramminginperlpossible,istakenfromTcl/TkTcl(ToolCommand
Language)andTk(ToolKit)wascreatedbyProfessorJohnOusterhoutoftheUniversityofCalifornia,BerkeleyTclisa
scriptinglanguagethatrunsonWindows,UNIXandMacintoshplatformsTkisastandardaddontoTclthatprovides
commandstoquicklyandeasilycreateuserinterfacesLateronTkwasusedbyalotofotherscriptinglanguageslike
Perl,Python,Rubyetc

Applications
PerlhasbeenusedsincetheearlydaysofthewebtowriteCGIscripts,andisnowacomponentofthepopularLAMP
(Linux/Apache/MySQL/Perl)platformforwebdevelopmentPerlhasbeencalled"thegluethatholdsthewebtogether"
LargesystemswritteninPerlincludeSlashdot,andearlyimplementationsofWikipediaandPHP
Perlfindsmanyapplicationsasagluelanguage,tyingtogethersystemsandinterfacesthatwerenotspecifically
designedtointeroperateSystemsadministratorsusePerlasanallpurposetool;shortPerlprogramscanbeenteredand
runonasinglecommandline

Philosophy
PerlhasseveralmottosthatconveyaspectsofitsdesignanduseOneisThere'smorethanonewaytodoit
(TMTOWTDIusuallypronounced'TimToady')AnotherisPerl:theSwissArmyChainsawofProgramming
LanguagesAstateddesigngoalofPerlisto"makeeasytaskseasyanddifficulttaskspossible"
Perlisfreesoftware,andmaybedistributedundereithertheArtisticortheGPLLicenseItisavailableformost
operatingsystemsbutisparticularlyprevalentonUnixandUnixlikesystems(suchasLinux,FreeBSD,andMacOS
X),andisgrowinginpopularityonMicrosoftWindowssystems

Perl/TkRequirements
Beforestartingwiththetutorial,makesureyouhavethefollowingthingsIfsomearemissingyoustillcanlearnperl
butyouwillnotbeabletouseittoitsfullpower
1. ActivePerlfromhttp://wwwactivestatecom/ActivePerl/forwindowsforprogramminginWindowsLinuxdon't
needanyspecialoutsideinterpreterbecauseitalreadyhasitinmostofthedistributions
2. AgoodtexteditorIwouldrecommendCrimsonEditor(http://wwwcrimsoneditorcom/)forWindowsand
XEmacsforLinux

Installing/UsingPerl
InUnix/Linuxyoucanexecuteyourperlscriptsbytyping"perl<filename>"atcommandpromptButbeforeyoudo
thatmakesureyouhavebothPerlanditsTkmoduleMostlinuxdistributionshaveperlbutquiteafewdon'thavethe
TkmoduleMakesurethatthesystemyouareusinghavetheTkmoduleIfyoudon'thaveit,gotohttp://wwwcpanorg
anddownloadtheperlmoduleOryoucanusetheperl'sCPANmoduletoinstalltheTkmoduleTodothis,opena
terminalandenterthefollowingcommand
perl -MCPAN -e shell
cpan> install Bundle::CPAN
cpan> reload cpan
cpan> install Tk
Another(andamucheasier)waytodothisistogetarpmofPerl/Tkandinstallingitwiththecommand
rpm -ivh FILENAME
IfyouareusingUbuntu,aeasywayofinstallingPerl/Tkisusingthiscommand
sudo apt-get install perl-tk
IfyouareusingWindows,downloadActivePerlandinstallitThenyoucanexecuteanyperlfilebydoubleclickingit
TwomorethingsbeforewebeginthetutorialIwillbeteachingperl/tkandIexpectyoutoknowhowtoprograminperl
Imayignoresomeoftheperlcodingconventionslikeincludinguse strict;,-woruse warnings;inmy
examplesTheexampleshaveonlyonepurposetodemonstratethefeaturethatwillbetaughtinthatpartofthe
tutorialSorryaboutthatbutIhavetokeepmytutorial'sexamplescriptsshortandtothepoint
Finally,thisisatutorialforPerl/TkonlyIwillnotbeteachingperlhereSoifyouknowperl,continueButifyouarea
beginnertoperl,Iwouldrecommendthatyoureadmyperltutorial

HelloWorld
Letusbegin,asallothertutorialsbegin,withthe"HelloWorld"programCreateafilecalled"Hellopl"andenterthe
followingintoit
#!/usr/local/bin/perl
use Tk;
# Main Window
my $mw = new MainWindow;
my $label = $mw -> Label(-text=>"Hello World") -> pack();
my $button = $mw -> Button(-text => "Quit",
-command => sub { exit })
-> pack();
MainLoop;

Thefirstline#!/usr/local/bin/perlisnotneededinwindowsInLinux,ittellsthenameofthescript
languageprocessorInourcaseitisperlDon'tunderstandwhatthatmeans?Don'tworryyourgraycellsoveritJustput
itatthetopofthefile
Thesecondlineuse Tk;tellstheinterpreterthatourprogramwillusetheTkmoduleThislineisanabsolutemust

inallGUIprogramsyoumakeusingperlWhentheinterpreterencountersthisline,itwillloadtheTkcomponentsthat
wewillbeusingtocreateourprogram
ThethirdlineThisisacommentAnylinethatstartswitha'#'charisacommentCommentsarenotofanyuseinthe
programItisusedbyprogrammertotalktothemselvesAprogrammercannotbeexpectedtoremembereverythinga
scriptdoesSoheusesacommenttowriteitdownNexttimeheeditsthescript,hecanreadthecommentand
understandwhattheprogramisforItisgoodpracticetomakeasmuchcommentsaspossible
Thefourthline,my $mw = new MainWindow;,willcreateawindowintowhichtheGUIelementswillbeplaced
Thevariable$mwisaobjectoftype'MainWindow'Wewillhavetousethiselementwhenwewanttoplaceany
widgetinsideit
Thefifthline$mw -> Label(-text=>"Hello World") -> pack();makesalabelandwrites"Hello
world"initYoucanchangethetexttoanythingyoulikeNotethestructureofthecommand
$labelThisvariableassignedtothatparticularwidgetEverwidgetmusthaveaUNIQUEvariableThisnamewill
beusedwheneverthatwidgetmustbeaccessed
$mw -> $mwistheMainWindow'sobjectWewillbeplacingourlabelwidgetinsidethiswindow
Label(-text=>"Hello World")'Label'isthenameofthewidgetAwidgetisauserinterfaceobjectinX
graphicaluserinterfacesConfused?LetsjustsaythatitisthenameoftheobjectthatappearsonscreenThereare
manyotherwidgetstooIfyouwanttodisplayabutton,youusethebuttonwidgetFortext,youusethetextwidgetFor
entry,youguessedit,theentrywidgetIfyouwant,youcanseemoreaboutwidgets
text=>"HelloWorld"TheoptionforthiswidgetThisoptionsaysthatthiswidgetmustbegiventhetext"Hello
World"Optionschangeaccordingtothewidgetsabuttonwidgetwillnothavealltheoptionsofthelabelwidgetand
viseversaButtherewillbemanycommonones
Pleasenotethatoperatorusedhereis'=>'asopposedtotheoneusedearlier'>'in$mw ->Oneusestheminus()sign
whiletheotherusestheequals(=)signDonotconfusebetweenthesetwo
YoucankeepwritingotheroptionscanalsobewrittenhereForexample,letusmakealabelforshowingthetext
"HelloWorld"TheotherlinesaresameastheHelloWorldprogram
$mw -> Label(-text=>"Hello World",-font=>"courierfont",-relief=>"raised") ->
pack();
Inthisexample,alotmoreoptionsareusedThefontoptionisusedtotellwhichfontmustbeusedtomakethetextand
thereliefoptiontellswhetherthetextshouldappearraised,sunken,flatetcToknowalltheoptionsforaparticular
widget,readthemanualthatcomeswithPerlItlistseverywidgetandeveryoptiontheyhaveIfyouaregoingto
programinPerl,youwillfindyourselfpeekingintothemanualeveryfewminutesThemostimportantandmost
commonlyusedoptionsarelistedhere
AlloptionsmustseparatedbyacommaButasyouhavenoted,thislineisalittledifficulttoreadAsthenumberof
optionsincrease,themoredifficulttoreaditSoamorereadableversionis
$mw -> Label(-text=>"Hello World",
-font=>"courierfont",
-relief=>"raised")
-> pack();

Nextcomesthe-> pack();Thiswillpackthewidget'$label'intothewindow'$mw''pack'isageometrymanager
Anothergeometrymanageris'grid'Personally,IlikegridbetterOnceagain,puttingallthisinonelineisaneyesore
soyoucanputthispartinthenextline
my $label = $mw -> Label(-text=>"Hello World")
-> pack();

Inthiscase,packhasnooptionswithinitButthatisnotalwaysthecase
my $label = $mw -> Label(-text=>"Hello World")
-> pack(-side=>"left",
-anchor=>'w');

Youdon'thavetopackthewidgetinthesamelineofcreatingitbutitisconvenientinsmallprogramsYoucanpack
thewidgetlaterusingthewidget'svariableForexample

my $label = $mw -> Label(-text=>"Hello World"); #We created the widget


$label -> pack(-side=>"left", -anchor=>'w'); #We pack it in another line

Sowehavethefinalsyntaxofhowtocreateanddisplayawidget
my $WidgetVariable = $Window -> WidgetType(?Option 1=>Value 1, ?Option 2=>Value
2 ??) -> pack();
Thenextthreelines
my $button = $mw -> Button(-text => "Quit",
-command => sub { exit })
-> pack();

willcreateanddisplayabuttonHerethewidgetvariableis'$button'Whenwelookattheoptions,wewillfindtwo
options'text'and'command'ThegiventextisQuitsothebuttonwillhavethetext"Quit"onitThecommandoption
determineswhatshouldhappenwhentheuserclickonthebuttonYoucanspecifyafunctiontoexecutewhentheuser
clicksonthebuttonInthiscasetheprogramwillexitwhenthisbuttonispressedOnecanalsocallfunctionsthatyou
havecreatedfromhere
#!/usr/local/bin/perl
use Tk;
# Main Window
my $mw = new MainWindow;
my $label = $mw -> Label(-text=>"Hello World") -> pack();
my $button = $mw -> Button(-text => "Quit",
-command =>\&exitProgam)
-> pack();
MainLoop;
sub exitProgam {
$mw->messageBox(-message=>"Goodbye");
exit;
}

ThenextlineMainLoop;istheMainLooportheEventLoopItsjobistoinvokecallbacksinresponsetoevents
suchasbuttonpressesortimerexpirationsIfthislineismissing,theprogramwillrunandexitwithoutwaitingforthe
usertodoanythingThisisanotheroneofthose'absolutemusts'ofPerl/Tkprogramming
NowPerlpuritanswillraiseagreathueandcryandsaythatthisisnotthewaytoprint"HelloWorld"The"pure"
methodisthefollowing
#!/usr/local/bin/perl
print "Hello World"
Puttingthingsinperspective,IamteachingPerl/TknotPerlTheaboveisthePerlmethodofdoingitMymethodis
thepTkmethodofdoingit

Widgets1:Button,Entry,Label
AwidgetisauserinterfaceobjectinXgraphicaluserinterfacesConfused?Letsjustsaythatitisthenameofthe
objectthatappearsonscreenTherearemanytypeswidgetsIfyouwanttodisplayabutton,youusethebuttonwidget
Fortext,youusethetextwidgetForentry,youguessedit,theentrywidget
Syntax:
my$WidgetVariable=$Window>WidgetType(?Option1=>Value1,?Option2=>Value2??)>pack();
ThreethingsneedtobesaidaboutwidgetsFirstisthewidgetvariableThisIhaveexplainedearlierThewidget
variableofallwidgetsmustbeuniqueandwillbeusedwheneverthatwidgetneedstobeaccessedSecondisthe
optionsEachwidgethassomeoptionswhichcanbeusedtoconfigureitThisisusuallydonewhenthewidgetis
declared,butitcanbedoneafterwardalsoThefinalthingiscommandsEachwidgethassomecommandswhichalso

canbeusedtoconfigureitormakeitdosomething
Butbeforewebegin,weneedtoknowalittleaboutthepackcommandIhaveexplainedthisearlierbutjustdoingit
onemoretimesothatyoudon'thavetopushthebackbuttonPackisageometrymanagerAnothergeometrymanager
is'grid'wewillexplorethatlatterPackismuchmoresimplerthangrid
Theline$hello>pack;tellstheinterpretertopackthewidgetcalled"$hello"

Button
ThiswillmakeabuttonItcanbeconfiguredtoexecutesomecodewhenthebuttonispushedThiswillusuallyreferto
afunctionsowhenthebuttonispushed,thefunctionwillrunAnbuttonisshownbelowThisbuttoniscreatedusing
HTMLinputtag
SomeOptions
text=>"TEXT"

TEXTwillbethetextdisplayedonthebutton

command=>CALLBACK CALLBACKwillbethecodethatiscalledwhenthebuttonispushed
#!/usr/local/bin/perl
use Tk;
# Main Window
my $mw = new MainWindow;
my $but = $mw -> Button(-text => "Push Me",
-command =>\&push_button);
$but -> pack();
MainLoop;
#This is executed when the button is pressed
sub push_button {
whatever
}

YoumayhavenoticedthatIusedaslash(\)inthecommandcallback(-command =>\&push_button);)Make
surethattheslashstaystheretoseewhy,gototheMostcommonmistakesbyPerl/Tkbeginners

Entry
AnentryisawidgetthatdisplaysaonelinetextstringandallowstheusertoinputandedittextinitWhenanentry
hastheinputfocusitdisplaysaninsertioncursortoindicatewherenewcharacterswillbeinsertedAnentryelementis
shownusingHTML
SomeOptions
width=>NUMBER

WidthoftheinputfieldNUMBERshouldbeaninteger

textvariable=>\$VARIABLE

ThecontentsofthevariableVARIABLEwillbedisplayedinthewidgetIfthetextin
thewidgetisedited,thevariablewillbeeditedautomatically

state=>STATE

ThestateoftheinputfieldItcanbenormal,disabled,orreadonlyIfitisreadonly
thetextcan'tbeedited

SomeCommands
Syntax

Description

Example

$widget>get();

Thetextinsideinputfieldcanbetakenbythis
command

$name=$ent>get();

$widget>delete(FIRST?,LAST?); DeleteoneormoreelementsoftheentryFIRSTis $ent>delete(0,'end');

theindexofthefirstcharactertodelete,andLAST
istheindexofthecharacterjustafterthelastone
todeleteIflastisn'tspecifieditdefaultsto
FIRST+1,ieasinglecharacterisdeletedThis
commandreturnsanemptystring
InsertthecharactersofSTRINGjustbeforethe
characterindicatedbyindexIndexis0forthefirst
$widget>insert(index,"STRING");
$ent>insert('end',"Hello");
characterTheword"end"canbeusedforthelast
character
Example
#!/usr/local/bin/perl
use Tk;
# Main Window
my $mw = new MainWindow;
#GUI Building Area
my $ent = $mw -> Entry() -> pack();
my $but = $mw -> Button(-text => "Push Me",
-command =>\&push_button);
$but -> pack();
MainLoop;
#This is executed when the button is pressed
sub push_button {
$ent -> insert('end',"Hello");
}

Label
Thiswidgetdisplaytextmessages
SomeOptions
text=>"TEXT" TEXTwillbethetextdisplayedonthebutton
font=>FONT

SpecifiesthefonttousewhendrawingtextinsidethewidgetYoucanspecifyjustthefontoryou
cangiveitinthisformat"FONTNAMESIZESTYLE"TheSTYLEcanbebold,normaletc

Example
#!/usr/local/bin/perl
use Tk;
my $mw = new MainWindow; # Main Window
my $lab = $mw -> Label(-text=>"Enter name:") -> pack();
my $ent = $mw -> Entry() -> pack();
my $but = $mw -> Button(-text => "Push Me",
-command =>\&push_button);
$but -> pack();
MainLoop;
#This is executed when the button is pressed
sub push_button {
$ent -> insert(0,"Hello, ");
}

Widgets2:Frame,Text,Scrollbar,Scale
Frame
AframeisasimplewidgetItsprimarypurposeistoactasaspacerorcontainerforcomplexwindowlayoutsTheonly
featuresofaframeareitsbackgroundcolorandanoptional3Dbordertomaketheframeappearraisedorsunken
Framecanbecreatedjustlikeanyotherwidget
my $frm = $mw -> Frame();
Toplaceotherwidgetsinthisframe,youshouldusetheframewidgetvariableasitsparentNormallytheparentis
'$mw'ortheMainWindowButifwewishtoputawidgetinsideaframe,usetheframevariable('$frm'inthiscase)in
placeof'$mw'Likethis
my $lab = $frm_name -> Label(-text=>"Name:") -> pack();
SomeOptions
Specifiesthe3DeffectdesiredforthewidgetAcceptablevaluesareraised,sunken,flat,ridge,
solid,andgrooveThevalueindicateshowtheinteriorofthewidgetshouldappearrelativetoits
relief=>STYLE
exterior;forexample,raisedmeanstheinteriorofthewidgetshouldappeartoprotrudefromthe
screen,relativetotheexteriorofthewidget
Example
#!/usr/local/bin/perl
use Tk;
my $mw = new MainWindow; # Main Window
my $frm_name = $mw -> Frame() -> pack(); #New Frame
my $lab = $frm_name -> Label(-text=>"Name:") -> pack();
my $ent = $frm_name -> Entry() -> pack();
my $but = $mw -> Button(-text=>"Push Me", -command =>\&push_button) -> pack();
MainLoop;
#This function will be executed when the button is pushed
sub push_button {
$ent -> insert(0,"Hello, ");
}

Text
AtextwidgetdisplaysoneormorelinesoftextandallowsthattexttobeeditedSimilartotheentrywidgetbutalarger
versionofit
SomeOptions
xscrollcommand=>COMMAND

Thisistoenablecommunicationbetweenatextwidgetandascrollbarwidget
Thereisayscrollcommandsimillertothisone

font=>FONTNAME

Specifiesthefonttousewhendrawingtextinsidethewidget

width=>NUMBER

Specifiesthewidthofthewidget

height=>NUMBER

Specifiesthe,youguessedit,heightofthewidget

Syntax

Description

Example

$widget>get(index1,?index2?);

Returnarangeofcharactersfromthetext
Thereturnvaluewillbeallthecharactersin
thetextstartingwiththeonewhoseindexis
index1andendingjustbeforetheonewhose
indexisindex2(thecharacteratindex2will
notbereturned)Ifindex2isomittedthenthe
singlecharacteratindex1isreturned
$contents=$txt>get(10,'end');
Notethattheindexoftextisdifferentfrom
thatoftheentrywidgetTheindexoftext
widgetisintheform
LINE_NOCHARECTER_NOThismeans
that10meansthefirstcharacterinthefirst
line

$widget>insert(index,DATA);

Insertsallofthecharsargumentsjustbefore
thecharacteratindexIfindexreferstothe
endofthetext(thecharacterafterthelast
$txt>inset('end',"HelloWorld");
newline)thenthenewtextisinsertedjust
beforethelastnewlineinstead

Example
#!/usr/local/bin/perl
use Tk;
my $mw = new MainWindow; # Main Window
my $frm_name = $mw -> Frame() -> pack();
my $lab = $frm_name -> Label(-text=>"Name:") -> pack();
my $ent = $frm_name -> Entry() -> pack();
my $but = $mw -> Button(-text=>"Push Me", -command =>\&push_button) -> pack();
#Text Area
my $txt = $mw -> Text(-width=>40, -height=>10) -> pack();
MainLoop;
#This function will be executed when the button is pushed
sub push_button {
my $name = $ent -> get();
$txt -> insert('end',"Hello, $name");
}

Scrollbar
Ascrollbarisawidgetthatdisplaystwoarrows,oneateachendofthescrollbar,andasliderinthemiddleportionof
thescrollbarItprovidesinformationaboutwhatisvisibleinanassociatedwindowthatdisplaysandocumentofsome
sort(suchasafilebeingeditedoradrawing)Thepositionandsizeofthesliderindicatewhichportionofthe
documentisvisibleintheassociatedwindowForexample,ifthesliderinaverticalscrollbarcoversthetopthirdof
theareabetweenthetwoarrows,itmeansthattheassociatedwindowdisplaysthetopthirdofitsdocumentItismade
toworkwithotherwidgetsliketextSomeOptions
orient=>DIRECTION

Forwidgetsthatcanlaythemselvesoutwitheitherahorizontalorverticalorientation,
suchasscrollbars,thisoptionspecifieswhichorientationshouldbeusedDIRECTION
mustbeeitherhorizontalorverticaloranabbreviationofoneofthese

command=>COMMAND ThiscommandgetsexecutedwhenthescrollbarismovedThisoptionalmostalwayshas

avaluesuchastxviewortyview,consistingofthenameofawidgetandeitherxview
(ifthescrollbarisforhorizontalscrolling)oryview(forverticalscrolling)Allscrollable
widgetshavexviewandyviewcommandsthattakeexactlytheadditionalarguments
appendedbythescrollbar

Example
#!/usr/local/bin/perl
use Tk;
my $mw = new MainWindow; # Main Window
my $frm_name = $mw -> Frame();
my $lab = $frm_name -> Label(-text=>"Name:");
my $ent = $frm_name -> Entry();
my $but = $mw -> Button(-text=>"Push Me", -command =>\&push_button);
my $textarea = $mw -> Frame(); #Creating Another Frame
my $txt = $textarea -> Text(-width=>40, -height=>10);
my $srl_y = $textarea -> Scrollbar(-orient=>'v',-command=>[yview => $txt]);
my $srl_x = $textarea -> Scrollbar(-orient=>'h',-command=>[xview => $txt]);
$txt -> configure(-yscrollcommand=>['set', $srl_y],
-xscrollcommand=>['set',$srl_x]);
$lab -> grid(-row=>1,-column=>1);
$ent -> grid(-row=>1,-column=>2);
$frm_name -> grid(-row=>1,-column=>1,-columnspan=>2);
$but -> grid(-row=>4,-column=>1,-columnspan=>2);
$txt -> grid(-row=>1,-column=>1);
$srl_y -> grid(-row=>1,-column=>2,-sticky=>"ns");
$srl_x -> grid(-row=>2,-column=>1,-sticky=>"ew");
$textarea -> grid(-row=>5,-column=>1,-columnspan=>2);
MainLoop;
#This function will be executed when the button is pushed
sub push_button {
my $name = $ent -> get();
$txt -> insert('end',"Hello, $name");
}

grid
AsyoucanseeIhaveused'grid'hereGridisNOTawidgetItisageometrymanagerlikepackbutmoreadvancedLets
takeacloserlookatthecommands
$widget -> grid(-row=>1, -column=>1);
Thislinewilltelltheinterpretertoputthewidgetcalled'$txt'inthefirstrowofthefirstcolumnofitsparentwidget
Thebelowdigramwillhelpyouunderstand
Column1
Column2
Row1 '$txt'widgetwillbehere '$srl_y'widget'splace
Row2 '$srl_x'widget'sposition

SomeOptions

sticky=>STYLE

Thisoptionmaybeusedtoposition(orstretch)thewidgetwithinitscellSTYLEisastringthat
containszeroormoreofthecharactersn,s,eorwEachletterreferstoaside(north,south,
east,orwest)thattheslavewill"stick"toIfbothnands(oreandw)arespecified,theslave
willbestretchedtofilltheentireheight(orwidth)ofitscavity

ipadx=>AMOUNT

TheAMOUNTspecifieshowmuchhorizontalinternalpaddingtoleaveoneachsideofthe
slave(s)Thisisspaceisaddedinsidetheslave(s)border

ipady=>AMOUNT

TheAMOUNTspecifieshowmuchverticalinternalpaddingtoleaveoneachsideofthe
slave(s)Optionssameasipadx

Theamountspecifieshowmuchhorizontalexternalpaddingtoleaveoneachsideofthe
padx=>AMOUNT slave(s),inscreenunitsAMOUNTmaybealistoftwovaluestospecifypaddingforleftand
rightseparately
pady=>AMOUNT

Theamountspecifieshowmuchverticalexternalpaddingtoleaveonthetopandbottomofthe
slave(s),inscreenunitsOptionssameaspadx

row=>N

InserttheslavesothatitoccupiestheNthrowinthegridRownumbersstartwith0Ifthis
optionisnotsupplied,thentheslaveisarrangedonthesamerowasthepreviousslave
specifiedonthiscalltogrid,orthefirstunoccupiedrowifthisisthefirstslave

column=>N

InserttheslavesothatitoccupiestheN'thcolumninthegridOptionssameasrow

rowspan=>N

InserttheslavesothatitoccupiesNrowsinthegridThedefaultisonerow

columnspan=>N

InserttheslavesothatitoccupiesNcolumnsinthegrid

UsinggridrequiresabitofexperiencebutifyouknowHTMLitwouldhelpalotTherowsandcolumnsarejustlike
thoseinHTMLtablesalthoughthecodesareverydifferent

Scale
Makesasliderthatcanbeadjustedbytheusertoinputavariable
SomeOptions
from=>NUMBER

StartingNumber

to=>NUMBER

EndingNumber

tickinterval=>NUMBER

Determinesthespacingbetweennumericaltickmarksdisplayedbelowortotheleftofthe
slider

varable=>NAME

SpecifiesthenameofaglobalvariabletolinktothescaleWheneverthevalueofthe
variablechanges,thescalewillupdatetoreflectthisvalueWheneverthescaleis
manipulatedinteractively,thevariablewillbemodifiedtoreflectthescale'snewvalue

Syntax

Description

$widget>get();

Getthecurrentvalueofthescale my$age=$scl>get();

$widget>set(value); Givethescaleanewvalue

Example
#!/usr/local/bin/perl
use Tk;
#Global Variables
my $age = 10;

Example
$scl>set(20);

# Main Window
my $mw = new MainWindow;
#GUI Building Area
my $frm_name = $mw -> Frame();
my $lab = $frm_name -> Label(-text=>"Name:");
my $ent = $frm_name -> Entry();
#Age
my $scl = $mw -> Scale(-label=>"Age :",
-orient=>'v',
-digit=>1,
-from=>10,
-to=>50,
-variable=>\$age,
-tickinterval=>10);
my $but = $mw -> Button(-text=>"Push Me", -command =>\&push_button);
#Text Area
my $textarea = $mw -> Frame();
my $txt = $textarea -> Text(-width=>40, -height=>10);
my $srl_y = $textarea -> Scrollbar(-orient=>'v',-command=>[yview => $txt]);
my $srl_x = $textarea -> Scrollbar(-orient=>'h',-command=>[xview => $txt]);
$txt -> configure(-yscrollcommand=>['set', $srl_y],
-xscrollcommand=>['set',$srl_x]);
#Geometry Management
$lab -> grid(-row=>1,-column=>1);
$ent -> grid(-row=>1,-column=>2);
$scl -> grid(-row=>2,-column=>1);
$frm_name -> grid(-row=>1,-column=>1,-columnspan=>2);
$but -> grid(-row=>4,-column=>1,-columnspan=>2);
$txt -> grid(-row=>1,-column=>1);
$srl_y -> grid(-row=>1,-column=>2,-sticky=>"ns");
$srl_x -> grid(-row=>2,-column=>1,-sticky=>"ew");
$textarea -> grid(-row=>5,-column=>1,-columnspan=>2);
MainLoop;
## Functions
#This function will be exected when the button is pushed
sub push_button {
my $name = $ent -> get();
$txt -> insert('end',"$name is $age years old");
}

NowourlittleexampleisbecomingmoreandmorelikeaprogramWehaveaddedthecommentstoitasithasgrown
bigandisdifficulttounderstandNowwehaveaddedasliderwithwhichagecanbeinputed

Dialogs
DialogscanbecalledtheelementsinaprogramthatdetachesitselffromthemainwindowThisisaVERYgeneral
definitionandhasmanyproblemsButforthemoment,itwilldoTkprovidesmanydialogs

messageBox
Thisprocedurecreatesanddisplaysamessagewindowwithanapplicationspecifiedmessage,aniconandasetof
buttonsEachofthebuttonsinthemessagewindowisidentifiedbyauniquesymbolicname(seethetypeoptions)
Afterthemessagewindowispoppedup,messageBoxwaitsfortheusertoselectoneofthebuttonsPushthebelow
buttontoseeanexampleofmessageBox
SomeOptions
default=>name

Namegivesthesymbolicnameofthedefaultbuttonforthismessagewindow('ok','cancel',
andsoon)SeetypeforalistofthesymbolicnamesIfthisoptionisnotspecified,thefirst

buttoninthedialogwillbemadethedefault
icon>iconImage

SpecifiesanicontodisplayIconImagemustbeoneofthefollowing:error,info,questionor
warningIfthisoptionisnotspecified,thentheinfoiconwillbedisplayed

message>string

Specifiesthemessagetodisplayinthismessagebox

title>String

SpecifiesastringtodisplayasthetitleofthemessageboxThedefaultvalueisanemptystring
ArrangesforapredefinedsetofbuttonstobedisplayedThefollowingvaluesarepossiblefor
predefinedType:
abortretryignore Displaysthreebuttonswhosesymbolicnamesareabort,retryandignore

ok
type>predefinedType okcancel

Displaysonebuttonwhosesymbolicnameisok
Displaystwobuttonswhosesymbolicnamesareokandcancel

retrycancel

Displaystwobuttonswhosesymbolicnamesareretryandcancel

yesno

Displaystwobuttonswhosesymbolicnamesareyesandno

yesnocancel

Displaysthreebuttonswhosesymbolicnamesareyes,noandcancel

Example
#!/usr/local/bin/perl
use Tk;
use strict;
# Main Window
my $mw = new MainWindow;
my $button = $mw-<Button(-text=<"Show Quit Dailog", -command =< \&exitTheApp)-<pack();
sub exitTheApp {
my $response = $mw -< messageBox(-message=<"Really quit?",-type=<'yesno',icon=<'question');
if( $response eq "Yes" ) {
exit
} else {
$mw -< messageBox(-type=<"ok", -message=<"I know you like this application!");
}
}
MainLoop;

chooseColor
chooseColorpopsupadialogboxfortheusertoselectacolor
SomeOptions
initialcolor>COLOUR Specifiesthecolortodisplayinthecolordialogwhenitpopsup

getOpenFile
TheproceduresgetOpenFileandgetSaveFilepopupadialogboxfortheusertoselectafiletoopenorsaveThe
getOpenFilecommandisusuallyassociatedwiththeOpencommandintheFilemenuItspurposeisfortheuserto
selectanexistingfileonlyIftheuserentersannonexistentfile,thedialogboxgivestheuseranerrorpromptand
requirestheusertogiveanalternativeselectionIfanapplicationallowstheusertocreatenewfiles,itshoulddosoby

providingaseparateNewmenucommand
ThegetSaveFilecommandisusuallyassociatedwiththeSaveascommandintheFilemenuIftheuserentersafilethat
alreadyexists,thedialogboxpromptstheuserforconfirmationwhethertheexistingfileshouldbeoverwrittenornot
SomeOptions
initialdir=>DIRNAME

Specifiesthatthedirectoriesindirectoryshouldbedisplayedwhenthedialogpops
upIfthisparameterisnotspecified,thenthedirectoriesinthecurrentworking
directoryaredisplayedIftheparameterspecifiesarelativepath,thereturnvalue
willconverttherelativepathtoanabsolutepath

Specifiesastringthatwillbeappendedtothefilenameiftheuserentersa
defaultextension=>EXTENSION filenamewithoutanextensionThedefaultvalueistheemptystring,whichmeans
noextensionwillbeappendedtothefilenameinanycase

filetypes=>filePatternList

IfaFiletypeslistboxexistsinthefiledialogontheparticularplatform,thisoption
givesthefiletypesinthislistboxWhentheuserchooseafiletypeinthelistbox,
onlythefilesofthattypearelistedIfthisoptionisunspecified,orifitissettothe
emptylist,oriftheFiletypeslistboxisnotsupportedbytheparticularplatform
thenallfilesarelistedregardlessoftheirtypesThisisalittletrickyseemanual
forinformation

initialfile=>FILENAME

Specifiesafilenametobedisplayedinthedialogwhenitpopsup

multiple

AllowstheusertochoosemultiplefilesfromtheOpendialog

Toplevel
toplevelisawidgetThiscanbeusedtocreatecustomdialogboxesAtoplevelissimilartoaframeexceptthatitis
createdasatoplevelwindow:itsXparentistherootwindowofascreenratherthanthelogicalparentfromitspath
nameTheprimarypurposeofatoplevelistoserveasacontainerfordialogboxesandothercollectionsofwidgetsThe
onlyvisiblefeaturesofatoplevelareitsbackgroundcolorandanoptional3Dbordertomakethetoplevelappear
raisedorsunken
OnecanusetopleveltocreatenewwindowsThewidgetscanbepackedinsideitinthesamewaywidgetsarepacked
insideaframeAnexample
#!/usr/local/bin/perl
use Tk;
# Main Window
$mw = new MainWindow;
my $lab = $mw -> Label(-text=>"This is the root window",
-font=>"ansi 12 bold") -> pack;
my $but = $mw -> Button(-text=>"Click to Create Toplevel",
-command=>\&makeTop) -> pack;
MainLoop;
#A function to make a toplevel window
sub makeTop {
my $top = $mw -> Toplevel(); #Make the window
#Put things in it
my $top_lab = $top -> Label(-text=>"This is the Toplevel window",
-font=>"ansi 12 bold") -> pack;
my $txt = $top -> Text() -> pack;
$txt -> insert('end', "Widgets can be packed in this window");

#An option to close the window


my $but_close = $top -> Button(-text=>"Close",
-command => sub { destroy $top; } ) -> pack;

Widgets3:Radiobutton,Checkbutton
Radiobutton
RadiobuttonisaninputwhereanyoneofmanychoicesMUSTbechosenIfoneischosenandanotherbuttonis
clicked,thelastchosenwillloseitsstateandtheclickedbuttonwillbechosenAgraphicexample(inHTML)isgiven
below
Choices 1| 2| 3
SomeOptions
command=>COMMAND

SpecifiesacommandtoassociatewiththebuttonThiscommandistypicallyinvoked
whenmousebutton1isreleasedoverthebuttonwindow

variable=>\$VARIABLE Specifiesnameofglobalvariabletosettoindicatewhetherornotthisbuttonisselected
value=>VALUE

Specifiesvaluetostoreinthebutton'sassociatedvariablewheneverthisbuttonisselected

Syntax

Description

Example

$widget>deselect();

Deselectsthecheckbuttonandsetstheassociatedvariabletoits"off"
value

$rdb_m>deselect();

$widget>select()

Selectsthecheckbuttonandsetstheassociatedvariabletoits"on"value $rdb_m>select();

Example
#!/usr/local/bin/perl
use Tk;
#Global Variables
my $age = 10;
my $gender = "Male";
# Main Window
my $mw = new MainWindow;
#GUI Building Area
my $frm_name = $mw -> Frame();
my $lab = $frm_name -> Label(-text=>"Name:");
my $ent = $frm_name -> Entry();
#Age
my $scl = $mw -> Scale(-label=>"Age :",
-orient=>'v',
-digit=>1,
-from=>10,
-to=>50,
-variable=>\$age,
-tickinterval=>10);
#Gender
my $frm_gender = $mw -> Frame();
my $lbl_gender = $frm_gender -> Label(-text=>"Sex ");
my $rdb_m = $frm_gender -> Radiobutton(-text=>"Male",
-value=>"Male", -variable=>\$gender);
my $rdb_f = $frm_gender -> Radiobutton(-text=>"Female",
-value=>"Female",-variable=>\$gender);
my $but = $mw -> Button(-text=>"Push Me", -command =>\&push_button);
#Text Area
my $textarea = $mw -> Frame();

my $txt = $textarea -> Text(-width=>40, -height=>10);


my $srl_y = $textarea -> Scrollbar(-orient=>'v',-command=>[yview => $txt]);
my $srl_x = $textarea -> Scrollbar(-orient=>'h',-command=>[xview => $txt]);
$txt -> configure(-yscrollcommand=>['set', $srl_y],
-xscrollcommand=>['set',$srl_x]);
#Geometry Management
$lab -> grid(-row=>1,-column=>1);
$ent -> grid(-row=>1,-column=>2);
$scl -> grid(-row=>2,-column=>1);
$frm_name -> grid(-row=>1,-column=>1,-columnspan=>2);
$lbl_gender -> grid(-row=>1,-column=>1);
$rdb_m -> grid(-row=>1,-column=>2);
$rdb_f -> grid(-row=>1,-column=>3);
$frm_gender -> grid(-row=>3,-column=>1,-columnspan=>2);
$but -> grid(-row=>4,-column=>1,-columnspan=>2);
$txt -> grid(-row=>1,-column=>1);
$srl_y -> grid(-row=>1,-column=>2,-sticky=>"ns");
$srl_x -> grid(-row=>2,-column=>1,-sticky=>"ew");
$textarea -> grid(-row=>5,-column=>1,-columnspan=>2);
MainLoop;
## Functions
#This function will be executed when the button is pushed
sub push_button {
my $name = $ent -> get();
$txt -> insert('end',"$name\($gender\) is $age years old");
}

ThistimetheprogramissubjectedtoevenmorechangethegeometrymanagerisfullygridnowThereisnoinstances
ofpackYouwillfindthisnecessarywhenthelayoutbecomesmorecomplicatedIhopeyoucanstaywithmeinsuch
tryingtimes

Checkbutton
CheckbottonisainputwithtwooptionsOfforOnithastobeeitheroneThestatecanbechangedbyclickingonit
Anexampleisshownbelow
checkbox
SomeOptions
offvalue=>VALUE

Specifiesvaluetostoreinthebutton'sassociatedvariablewheneverthisbuttonis
deselectedDefaultsto``0''

onvalue=>VALUE

Specifiesvaluetostoreinthebutton'sassociatedvariablewheneverthisbuttonisselected
Defaultsto``1''

command=>CALLBACK

SpecifiesacommandtoassociatewiththebuttonThiscommandistypicallyinvoked
whenmousebutton1isreleasedoverthebuttonwindow

variable=>\$VARABLE

Specifiesnameofglobalvariabletosettoindicatewhetherornotthisbuttonisselected

Syntax

Description

Example

$widget>deselect(); Deselectsthecheckbuttonandsetstheassociatedvariabletoits``off''value

$chk>
deselect();

$widget>select();

$chk>select();

Selectsthecheckbuttonandsetstheassociatedvariabletoits``on''value

$widget>toggle();

Togglestheselectionstateofthebutton,redisplayingitandmodifyingits
associatedvariabletoreflectthenewstate

Example
#!/usr/local/bin/perl
use Tk;
#Global Variables
my $age = 10;
my $gender = "Male";
my $occupied = 1;
# Main Window
my $mw = new MainWindow;
#GUI Building Area
my $frm_name = $mw -> Frame();
my $lab = $frm_name -> Label(-text=>"Name:");
my $ent = $frm_name -> Entry();
#Age
my $scl = $mw -> Scale(-label=>"Age :",
-orient=>'v',
-digit=>1,
-from=>10,
-to=>50,
-variable=>\$age,
-tickinterval=>10);
#Jobs
my $chk = $mw -> Checkbutton(-text=>"Occupied",
-variable=>\$occupied);
$chk -> deselect();
#Gender
my $frm_gender = $mw -> Frame();
my $lbl_gender = $frm_gender -> Label(-text=>"Sex ");
my $rdb_m = $frm_gender -> Radiobutton(-text=>"Male",
-value=>"Male", -variable=>\$gender);
my $rdb_f = $frm_gender -> Radiobutton(-text=>"Female",
-value=>"Female",-variable=>\$gender);
my $but = $mw -> Button(-text=>"Push Me", -command =>\&push_button);
#Text Area
my $textarea = $mw -> Frame();
my $txt = $textarea -> Text(-width=>40, -height=>10);
my $srl_y = $textarea -> Scrollbar(-orient=>'v',-command=>[yview => $txt]);
my $srl_x = $textarea -> Scrollbar(-orient=>'h',-command=>[xview => $txt]);
$txt -> configure(-yscrollcommand=>['set', $srl_y],
-xscrollcommand=>['set',$srl_x]);
#Geometry Management
$lab -> grid(-row=>1,-column=>1);
$ent -> grid(-row=>1,-column=>2);
$frm_name -> grid(-row=>1,-column=>1,-columnspan=>2);
$scl -> grid(-row=>2,-column=>1);
$chk -> grid(-row=>2,-column=>2,-sticky=>'w');
$lbl_gender -> grid(-row=>1,-column=>1);
$rdb_m -> grid(-row=>1,-column=>2);
$rdb_f -> grid(-row=>1,-column=>3);
$frm_gender -> grid(-row=>3,-column=>1,-columnspan=>2);
$but -> grid(-row=>4,-column=>1,-columnspan=>2);
$txt -> grid(-row=>1,-column=>1);
$srl_y -> grid(-row=>1,-column=>2,-sticky=>"ns");

$chk>toggle();

$srl_x -> grid(-row=>2,-column=>1,-sticky=>"ew");


$textarea -> grid(-row=>5,-column=>1,-columnspan=>2);
MainLoop;
## Functions
#This function will be executed when the button is pushed
sub push_button {
my $name = $ent -> get();
$txt -> insert('end',"$name\($gender\) is $age years old");
}

Widgets4:Listbox
Listbox
Alistboxisawidgetthatdisplaysalistofstrings,oneperlineWhenfirstcreated,anewlistboxhasnoelements
Elementsmaybeaddedordeletedusingwidgetcommandsdescribedbelow
SomeOptions
SpecifiesoneofseveralstylesformanipulatingtheselectionTheMODEmaybearbitrary,
selectmode=>MODE butthedefaultbindingsexpectittobeeithersingle,browse,multiple,orextended;the
defaultvalueisbrowse

SomeCommands
Syntax

Description

Example

$widget>curselection();

Returnsalistcontainingthenumericalindicesofallof
theelementsinthelistboxthatarecurrentlyselectedIf
$sel=$lst>curselection();
therearenoelementsselectedinthelistboxthenan
emptystringisreturned

DeletesoneormoreelementsofthelistboxFirstandlast
areindicesspecifyingthefirstandlastelementsinthe
$widget>delete(first,?last?);
$lst>delete(5);
rangetodeleteIflastisn'tspecifieditdefaultstofirst,ie
asingleelementisdeleted

$widget>get(first,?last?);

Iflastisomitted,returnsthecontentsofthelistbox
elementindicatedbyfirst,oranemptystringiffirst
referstoanonexistentelementIflastisspecified,the
commandreturnsalistwhoseelementsareallofthe
listboxelementsbetweenfirstandlast,inclusive

$widget>index(index);

Returnstheintegerindexvaluethatcorrespondstoindex
Ifindexisendthereturnvalueisacountofthenumber
$lst>index(5);
ofelementsinthelistbox(nottheindexofthelast
element)

$widget>insert(index,?
elementelement?);

Insertszeroormorenewelementsinthelistjustbefore
theelementgivenbyindexIfindexisspecifiedasend
$lst>insert('end',"me");
thenthenewelementsareaddedtotheendofthelist
Returnsanemptystring

$widget>size();

Returnsadecimalstringindicatingthetotalnumberof
$count=$lst>size();
elementsinthelistbox

Example

$lst>get(5,end);

#!/usr/local/bin/perl
use Tk;
#Global Variables
my $age = 10;
my $occupied = 1;
my $gender = "Male";
# Main Window
my $mw = new MainWindow;
#GUI Building Area
my $frm_name = $mw -> Frame();
my $lab = $frm_name -> Label(-text=>"Name:");
my $ent = $frm_name -> Entry();
#Age
my $scl = $mw -> Scale(-label=>"Age :",
-orient=>'v',
-digit=>1,
-from=>10,
-to=>50,
-variable=>\$age,
-tickinterval=>10);
#Jobs
my $frm_job = $mw -> Frame();
my $chk = $frm_job -> Checkbutton(-text=>"Occupied",
-variable=>\$occupied);
$chk -> deselect();
my $lst = $frm_job -> Listbox(-selectmode=>'single');
#Adding jobs
$lst -> insert('end',"Student","Teacher","Clerk","Business Man",
"Militry Personal","Computer Expert","Others");
#Gender
my $frm_gender = $mw -> Frame();
my $lbl_gender = $frm_gender -> Label(-text=>"Sex ");
my $rdb_m = $frm_gender -> Radiobutton(-text=>"Male",
-value=>"Male", -variable=>\$gender);
my $rdb_f = $frm_gender -> Radiobutton(-text=>"Female",
-value=>"Female",-variable=>\$gender);
my $but = $mw -> Button(-text=>"Push Me", -command =>\&push_button);
#Text Area
my $textarea = $mw -> Frame();
my $txt = $textarea -> Text(-width=>40, -height=>10);
my $srl_y = $textarea -> Scrollbar(-orient=>'v',-command=>[yview => $txt]);
my $srl_x = $textarea -> Scrollbar(-orient=>'h',-command=>[xview => $txt]);
$txt -> configure(-yscrollcommand=>['set', $srl_y],
-xscrollcommand=>['set',$srl_x]);
#Geometry Management
$lab -> grid(-row=>1,-column=>1);
$ent -> grid(-row=>1,-column=>2);
$scl -> grid(-row=>2,-column=>1);
$frm_name -> grid(-row=>1,-column=>1,-columnspan=>2);
$chk -> grid(-row=>1,-column=>1,-sticky=>'w');
$lst -> grid(-row=>2,-column=>1);
$frm_job -> grid(-row=>2,-column=>2);
$lbl_gender -> grid(-row=>1,-column=>1);
$rdb_m -> grid(-row=>1,-column=>2);
$rdb_f -> grid(-row=>1,-column=>3);
$frm_gender -> grid(-row=>3,-column=>1,-columnspan=>2);
$but -> grid(-row=>4,-column=>1,-columnspan=>2);
$txt -> grid(-row=>1,-column=>1);
$srl_y -> grid(-row=>1,-column=>2,-sticky=>"ns");

$srl_x -> grid(-row=>2,-column=>1,-sticky=>"ew");


$textarea -> grid(-row=>5,-column=>1,-columnspan=>2);
MainLoop;
## Functions
#This function will be executed when the button is pushed
sub push_button {
my $name = $ent -> get();
$txt -> insert('end',"$name\($gender\) is $age years old and is ");
my $job = "";
#See whether he is employed
if ( $occupied == 1 ) {
my $job_id = $lst -> curselection(); #Get the no of selected jobs
if ( $job_id eq "" ) { #If there is no job
$job = "a Non worker";
}
else {
$job = $lst -> get($job_id) ;#Get the name of the job
$txt -> insert('end',"a $job");
}
}
else {
$txt -> insert('end',"unemployed");
}
}

Wow!Our'little'exampleisabig(andutterlypointless)programnowIamgoingtostop'exampling'fromnowon
Thisisquitecomplicatedisn'tit?Whydon'tyourunthescriptandseewhatabeautifulscriptwemadeCopytheabove
scriptandpasteitinafilecalled"infopl"anddoubleclickthefileVoila!WearePerl/Tkprogrammers

Widgets5:Menubutton,Menu,Optionmenu
Menubutton
Amenubuttonisawidgetthatdisplaysatextualstring,bitmap,orimageandisassociatedwithamenuwidgetIn
normalusage,pressingleftclickingthemenubuttoncausestheassociatedmenutobepostedjustunderneaththe
menubutton
SomeOptions
Specifieswherethemenuisgoingtobepopupupabovetriestopopthemenuabovethe
menubuttonbelowtriestopopthemenubelowthemenubuttonlefttriestopopthemenu
direction=>DIRECTION
totheleftofthemenubuttonrighttriestopopthemenutotherightofthemenubutton
flushpopsthemenudirectlyoverthemenubutton
menu=>NAME

SpecifiesthepathnameofthemenuassociatedwiththismenubuttonThemenumustbe
achildofthemenubutton

Menu
AmenuisawidgetthatdisplaysacollectionofonelineentriesarrangedinoneormorecolumnsThereexistseveral
differenttypesofentries,eachwithdifferentpropertiesEntriesofdifferenttypesmaybecombinedinasinglemenu
MenuentriesarenotthesameasentrywidgetsInfact,menuentriesarenotevendistinctwidgets;theentiremenuis
onewidget
SomeOptions

Thisoptionmusthaveaproperbooleanvalue,whichspecifieswhetherornotthemenu
shouldincludeatearoffentryatthetopIfso,itwillexistasentry0ofthemenuandthe
tearoff=>BOOLEAN
otherentrieswillnumberstartingat1Thedefaultmenubindingsarrangeforthemenutobe
tornoffwhenthetearoffentryisinvoked
title=>STRING

ThestringwillbeusedtotitlethewindowcreatedwhenthismenuistornoffIfthetitleis
NULL,thenthewindowwillhavethetitleofthemenubuttonorthetextofthecascadeitem
fromwhichthismenuwasinvoked

type=>OPTION

Thisoptioncanbeoneofmenubar,tearoff,ornormal,andissetwhenthemenuiscreated
Whilethestringreturnedbytheconfigurationdatabasewillchangeifthisoptionischanged,
thisdoesnotaffectthemenuwidget'sbehavior

SomeCommands
Syntax

Description

$widget>TYPE(?option=>
value,option=>value,?);

AddanewentrytothebottomofthemenuThenewentry'stypeisgivenbyTYPE
andmustbeoneofcascade,checkbutton,command,radiobutton,orseparator,
orauniqueabbreviationofoneoftheaboveIfadditionalargumentsarepresent,they
specifyanyofthefollowingoptions:
Specifiesastringtodisplayattherightsideofthemenu
entryNormallydescribesanacceleratorkeystroke
accelerator=>VALUE sequencethatmaybetypedtoinvokethesamefunction
asthemenuentryThisoptionisnotavailablefor
separatorortearoffentries
Whenthisoptioniszero,theappearsbelowtheprevious
columnbreak=>VALUE entryWhenthisoptionisone,themenuappearsatthe
topofanewcolumninthemenu
Specifiesastringtodisplayasanidentifyinglabelinthe
label=>VALUE
menuentryNotavailableforseparatorortearoffentries
Specifieswhetherthemenuentryshoulddisplaybothan
imageandtext,andifso,wheretheimageshouldbe
compound=>VALUE
placedrelativetothetextValidvaluesforthisoptionare
bottom,center,left,none,rightandtop
Specifiesanimagetodisplayinthemenuinsteadofa
textstringorbitmapTheimagemusthavebeencreated
bysomepreviousinvocationofimagecreateThisoption
image=>VALUE
overridesthelabelandbitmapoptionsbutmaybereset
toanemptystringtoenableatextualorbitmaplabelto
bedisplayedThisoptionisnotavailableforseparatoror
tearoffentries
Specifiestheintegerindexofacharactertounderlinein
theentryThisoptionisusedtomakekeyboardshortcuts
underline=>VALUE
0correspondstothefirstcharacterofthetextdisplayed
intheentry,1tothenextcharacter,andsoon

$widget>delete(index1,
?index2?);

Deleteallofthemenuentriesbetweenindex1andindex2inclusiveIfindex2is
omittedthenitdefaultstoindex1Attemptstodeleteatearoffmenuentryare
ignored(instead,youshouldchangethetearOffoptiontoremovethetearoffentry)

$widget>insert(index,type,?
option=>value?);

Sameastheaddwidgetcommandexceptthatitinsertsthenewentryjustbeforethe
entrygivenbyindex,insteadofappendingtotheendofthemenuThetype,option,
andvalueargumentshavethesameinterpretationasfortheaddwidgetcommandIt
isnotpossibletoinsertnewmenuentriesbeforethetearoffentry,ifthemenuhas
one

Example
#!/usr/local/bin/perl
use Tk;
# Main Window
my $mw = new MainWindow;
#Making a text area
my $txt = $mw -> Scrolled('Text',-width => 50,-scrollbars=>'e') -> pack ();
#Declare that there is a menu
my $mbar = $mw -> Menu();
$mw -> configure(-menu => $mbar);
#The Main Buttons
my $file = $mbar -> cascade(-label=>"File", -underline=>0, -tearoff => 0);
my $others = $mbar -> cascade(-label =>"Others", -underline=>0, -tearoff => 0);
my $help = $mbar -> cascade(-label =>"Help", -underline=>0, -tearoff => 0);
## File Menu ##
$file -> command(-label => "New", -underline=>0,
-command=>sub { $txt -> delete('10','end');} );
$file -> checkbutton(-label =>"Open", -underline => 0,
-command => [\&menuClicked, "Open"]);
$file -> command(-label =>"Save", -underline => 0,
-command => [\&menuClicked, "Save"]);
$file -> separator();
$file -> command(-label =>"Exit", -underline => 1,
-command => sub { exit } );
## Others Menu ##
my $insert = $others -> cascade(-label =>"Insert", -underline => 0, -tearoff => 0);
$insert -> command(-label =>"Name",
-command => sub { $txt->insert('end',"Name : Binny V A\n");});
$insert -> command(-label =>"Website", -command=>sub {
$txt->insert('end',"Website : http://wwwgeocitiescom/binnyva/\n");});
$insert -> command(-label =>"Email",
-command=> sub {$txt->insert('end',"E-Mail : binnyva\@hotmailcom\n");});
$others -> command(-label =>"Insert All", -underline => 7,
-command => sub { $txt->insert('end',"Name : Binny V A
Website : http://wwwgeocitiescom/binnyva/
E-Mail : binnyva\@hotmailcom");
});
## Help ##
$help -> command(-label =>"About", -command => sub {
$txt->delete('10','end');
$txt->insert('end',
"About
---------This script was created to make a menu for a\nPerl/Tk tutorial
Made by Binny V A
Website : http://wwwgeocitiescom/binnyva/code
E-Mail : binnyva\@hotmailcom"); });
MainLoop;
sub menuClicked {
my ($opt) = @_;
$mw->messageBox(-message=>"You have clicked $opt
This function is not implanted yet");
}

CreatethemainbuttonsascascademenusandcreatethemenusastheirslavesFormoreinformationseethemanual

Optionmenu
Makesabutton,whichwhenclickedonshowsalistwithavailableoptionsUsefulwhenuserhastomakeonechoice
whenmultiplechoicesaregivenBelowisaoptionsmenuinHTMLAwordofcautionthoughPerl/Tk'soptionmenu
hasaverydifferentappearance
Select from menu

Go

Syntax
my $widget = $mw -> Optionmenu(?option=>value,option=>value,?);
Options
Syntax

Description

options=>OPTIONS

(Re)setsthelistofoptionspresented

command=>CALLBACK Definesthecallbackthatisinvokeswhenanewoptionisselected
variable=>\$VARIABLE Referencetoascalarthatcontainsthecurrentvalueoftheselectedoption

Methords
Syntax

Description

Example

$widget>
addOptions([Option1=>Value1],?
[Option2=>Value2]?);

Addsnewlygivenoptionstothe
alreadyavailableoptions

$opt>addOptions([May=>5],
[June=>6],[July=>7],[Augest=>8]);

Example
#!/usr/local/bin/perl
use Tk;
# Main Window
$mw = new MainWindow;
my $var;
my $opt = $mw -> Optionmenu(-options => [qw(January February March April)],
-command => sub { print "got: ", shift, "\n" },
-variable => \$var,
)->pack;
$opt->addOptions([May=>5],[June=>6],[July=>7],[Augest=>8]);
$mw->Label(-textvariable=>\$var, -relief=>'groove')->pack;
$mw->Button(-text=>'Exit', -command=>sub{$mw->destroy})->pack;
MainLoop;

SomemoreWidgetsCanvas,Message,Adjuster,
Scrolled
Canvas
ThecanvaswidgetisaveryimportantwidgetasallpointsareaddressablegraphicaldrawingareaCanvaswidgets
implementstructuredgraphicsAcanvasdisplaysanynumberofitems,whichmaybethingslikerectangles,circles,
lines,andtextItemsmaybemanipulated(egmovedorrecolored)andcommandsmaybeassociatedwithitemsSoif
youdon'tlikethepaintprograminwindows,youcanmakeyourownprogramusingthiswidget

Thecommand$widget -> create typeoptionsisusedtomakedifferentstructuresAfewexamplesaregiven


belowFormoreinformationreadthemanual
Example
#!/usr/local/bin/perl
use Tk;
# Main Window
my $mw = new MainWindow;
my $cns = $mw -> Canvas(-relief=>"sunken", -background=>"blue");
$cns -> create('polygon',5,100,50,5,150,5,200,100,5,100,
-joinstyle=>"bevel", -fill=>"red", -outline=>"white", -width=>5);
$cns -> create('oval',200,100,300,200, -fill=>"green");
$cns -> create('oval',100,150,300,100, -fill=>"white", -width=>0);
$cns -> create('rectangle',10,150,100,250, -dash=>[6,4,2,4,2,4]);
$cns -> pack;
MainLoop;

Message
AmessageisawidgetthatdisplaysatextualstringMuchlikethelabelwidgetbutthiscanbeusedtomakeamultiline
text
ThejustifyoptionspecifieshowtojustifylinesoftextMustbeoneofleft,center,orrightDefaultstoleftThisoption
workstogetherwiththeanchor,aspect,padX,padY,andwidthoptionstoprovideavarietyofarrangementsofthetext
withinthewindow

Adjuster
AnadjusteractsliketheframewidgetwithonenotableexceptionTheborderscanbedraggedandexpendedThis
widgetcontainsanynumberofpanes,arrangedhorizontallyorvertically,accordingtothevalueoftheorientoption
Eachpanecontainsonewidget,andeachpairofpanesisseparatedbyamovablesashMovingasashcanbedoneby
draggingitThiscausesthewidgetsoneithersideofthesashtoberesized
SomeOptions
SpecifiesthesideonwhichthemanagedwidgetliesrelativetotheAdjusterInconjunctionwith
side=>DIRECTION thepackgeometrymanager,thisrelatestothesideofthemasteragainstwhichthemanaged
widgetandtheAdjusterarepackedMustbeleft,right,top,orbottomDefaultstotop
SomeMethods
ThiscommandconfigurestheAdjuster'swidgetandsideoptions
respectivelyto'$widget'andthesidevaluespecifiedin
$adjuster>packAfter($widget,?pack_options?)
pack_options(topifnotspecified)ItthenpackstheAdjusterafter
'$widget',withfillsettoxoryasappropriate
Example
use Tk;
use Tk::Adjuster;
my $mw = new MainWindow;
my $adj = $mw -> Adjuster();
my $lst = $mw -> Listbox();

$lst
$lst
$lst
$lst
$lst

->
->
->
->
->

insert('end',
insert('end',
insert('end',
insert('end',
insert('end',

"Item
"Item
"Item
"Item
"Item

1");
2");
3");
4");
5");

my $txt = $mw -> Scrolled("Text",-scrollbars=>'e');


$txt -> insert('end',"To Hack With It
To Compute
Or Not To Compute
That Is The Question
Whether 'Tis Nobler In The Memory Bank
To Suffer The Slings And Circuits Of Outrageous Functions
Or To Take Up Arms Against A Sea OfTransistors,
Or Rather Transponders
Transcondu-Trans
Er
Oh, To Hack With It");
my $side = "left";
$lst -> pack(-side => $side, -fill => 'both', -expand => 1);
$adj -> packAfter($lst, -side => $side);
$txt -> pack(-side => $side, -fill => 'both', -expand => 1);
MainLoop;

Scrolled
Scrolledisaderivedwidgetthatcreatesawidgetwithattachedscrollbar(s)Ifyouhavetriedtocreateawidgetand
attachscrollbarstoit,youwilldoubtlesslyunderstandtheusefulnessofthisfeatureItgreatlyreducesthenumberof
codeforthesesituations
my $widget = $parent -> Scrolled('WIDGET' ?,-scrollbars=>WHERE? ?,?);
WIDGETcanbeanywidgetthatsupportsscrollingForexample,Text,Listbox,etc
SomeOptions
Expectsasargumentthepositionwherethescrollbarsshouldbecreated:w,eorn,sora
scrollbars=>SIDE combinationofthemIftheoneorbothpositionsareprefixedwithothescrollbarwillonlyshow
upifthereisa'real'needtoscroll
Example:
use Tk;
my $mw = new MainWindow;
my $txt = $mw -> Scrolled('Text',-scrollbars=>"oe") -> pack;
$txt -> insert('end',
"Arthur: \"It's at times like this I wish I'd listened to my mother\"
Ford : \"Why, what did she say?\"
Arthur: \"I don't know, I never listened\"
Douglas Adams");
MainLoop;

Thesameexampleusinghandcodedscrollbars
use Tk;
my $mw = new MainWindow;

my $textarea = $mw -> Frame();


my $txt = $textarea -> Text(-width=>40, -height=>10);
my $srl_y = $textarea -> Scrollbar(-orient=>'v',-command=>[yview => $txt]);
my $srl_x = $textarea -> Scrollbar(-orient=>'h',-command=>[xview => $txt]);
$txt -> configure(-yscrollcommand=>['set', $srl_y],
-xscrollcommand=>['set',$srl_x]);
$txt -> insert('end',
"Arthur: \"It's at times like this I wish I'd listened to my mother\"
Ford : \"Why, what did she say?\"
Arthur: \"I don't know, I never listened\"
Douglas Adams");
#Geometry
$txt -> grid(-row=>1,-column=>1);
$srl_y -> grid(-row=>1,-column=>2,-sticky=>"ns");
$srl_x -> grid(-row=>2,-column=>1,-sticky=>"ew");
$textarea -> grid(-row=>1,-column=>1,-columnspan=>2);
MainLoop;

Asyoucansee,theScrolledwidgetsavesquiteabitoftyping

GeometryManagement:Grid,Pack
grid
Thegridcommandisusedtocommunicatewiththegridgeometrymanagerthatarrangeswidgetsinrowsandcolumns
insideofanotherwindow,calledthegeometrymaster(ormasterwindow)Thegridcommandcanhaveanyofseveral
forms,dependingontheoptionargument
Inshort,gridisthenamegiventothethingythatwillplaceyourwidgetwhereyouwantittobeplaced
SomeOptions
sticky=>STYLE

Thisoptionmaybeusedtoposition(orstretch)thewidgetwithinitscellSTYLEisastringthat
containszeroormoreofthecharactersn,s,eorwEachletterreferstoaside(north,south,
east,orwest)thattheslavewill"stick"toIfbothnands(oreandw)arespecified,theslave
willbestretchedtofilltheentireheight(orwidth)ofitscavity

ipadx=>AMOUNT

TheAMOUNTspecifieshowmuchhorizontalinternalpaddingtoleaveoneachsideofthe
slave(s)Thisisspaceisaddedinsidetheslave(s)border

ipady=>AMOUNT

TheAMOUNTspecifieshowmuchverticalinternalpaddingtoleaveoneachsideofthe
slave(s)Optionssameasipadx

Theamountspecifieshowmuchhorizontalexternalpaddingtoleaveoneachsideofthe
padx=>AMOUNT slave(s),inscreenunitsAMOUNTmaybealistoftwovaluestospecifypaddingforleftand
rightseparately
pady=>AMOUNT

Theamountspecifieshowmuchverticalexternalpaddingtoleaveonthetopandbottomofthe
slave(s),inscreenunitsOptionssameaspadx

row=>N

InserttheslavesothatitoccupiestheNthrowinthegridRownumbersstartwith0Ifthis
optionisnotsupplied,thentheslaveisarrangedonthesamerowasthepreviousslave
specifiedonthiscalltogrid,orthefirstunoccupiedrowifthisisthefirstslave

column=>N

InserttheslavesothatitoccupiestheN'thcolumninthegridOptionssameasrow

rowspan=>N

InserttheslavesothatitoccupiesNrowsinthegridThedefaultisonerow

columnspan=>N

InserttheslavesothatitoccupiesNcolumnsinthegrid

Example
#!/usr/local/bin/perl
use Tk;

# Main Window
my $mw = new MainWindow;
#Text Area
my $txt = $mw -> Text(-width=>40, -height=>10);
my $srl_y = $mw -> Scrollbar(-orient=>'v',-command=>[yview => $txt]);
my $srl_x = $mw -> Scrollbar(-orient=>'h',-command=>[xview => $txt]);
$txt -> configure(-yscrollcommand=>['set', $srl_y],
-xscrollcommand=>['set',$srl_x]);
#Geometry Management
$txt -> grid(-row=>1,-column=>1);
$srl_y -> grid(-row=>1,-column=>2,-sticky=>"ns");
$srl_x -> grid(-row=>2,-column=>1,-sticky=>"ew");
MainLoop;

Letstakeacloserlookatthecommands
$txt>grid(row=>1,column=>1);
Thislinewilltelltheinterpretertoputthewidgetcalled'$txt'inthefirstrowofthefirstcolumnofitsparentwidget
Thebelowdigramwillhelpyouunderstand
Column1
Column2
Row1 '$xt'widgetwillbehere '$srl_y'widget'splace
Row2 '$srl_x'widget'sposition
UsinggridrequiresabitofexperiencebutifyouknowHTMLitwouldhelpalotTherowsandcolumnsarejustlike
thoseinHTMLtablesTheconceptisthesamebutthecodesareverydifferent

pack
PackisalsoageometrymanagerlikeGridbutmuchsimplerYoudon'thavetospecifytherowsandcolumnsasyou
didforgridThisisforyoulazybonesoutthereJustput$widget -> pack;andthewidgetwillbepackedButfor
morecomplexarrangementswithpackonemustuseframes
SomeOptions
Specifieswhethertheslavesshouldbeexpandedtoconsumeextraspaceintheirmaster
expand=>BOOLEAN Soundsalotlikeslaveseatinguptheirmasters,don'tit?Itjustmeansthatwhenthe
applicationisresizedthewidgetswillautomaticallyfillthespace
fill=>STYLE

Thiswillstretchthewidgetinxdirection,ydirectionorbothdirections

side=>SIDE

Specifieswhichsideofthemastertheslave(s)willbepackedagainstMustbeleft,right,top,
orbottomDefaultstotop

Nowfortheexample
#!/usr/local/bin/perl
use Tk;
# Main Window
my $mw = new MainWindow;
my $lab = $mw -> Label(-text=>"Do You Remember When");
my $txt = $mw -> Text();
$txt->insert('end',"A Computer Was Something On TV From A Science Fiction Show
A Window Was Something You Hated To Clean
And Ram Was The Cousin Of A Goat

Meg
And
Now
And

Was The Name Of My Girlfriend


Gig Was Your Thumb Upright
They All Mean Different Things
That Mega Bytes

An Application Was For Employment


A Program Was A TV Show
A Cursor Used Profanity
A Keyboard Was A Piano
Compress Was Something You Did To The Garbage
Not Something You Did To A File
And If You Unzipped Anything In Public
You'd Be In Jail For A While
Log On Was Adding Wood To The
Hard Drive Was A Long Trip On
A Mouse Pad Was Where A Mouse
And A Backup Happened To Your

Fire
The Road
Lived
Commode

Cut You Did With A Pocket Knife


Paste You Did With Glue
A Web Was A Spider's Home
And A Virus Was The Flu
I Guess I'll Stick To My Pad And Paper
And The Memory In My Head
I Hear Nobody's Been Killed In A Computer Crash
But, When It Happens They Wish They Were Dead");
my $srl = $mw -> Scrollbar(-command=>[$txt,'yview']);
$txt -> configure(-yscrollcommand=>[$srl,'set']);
#The
$lab
$txt
$srl

packing commands
-> pack;
-> pack(-expand => 1, -fill => "both", -side => "left");
-> pack(-expand => 1, -fill => "y");

MainLoop;

SomeCommonWidgetOptions
ThecapitalizedwordmustbereplacedwithanyoftheboldwordsCheckthemanualforalltheoptionsAlsomakesure
thatthewidgetyouareusingsupporttheoptionyouareusing
anchor=>POSITION

Positionwidgetrelativeto:nnenwssesweworcenter

background=>COLOR

Backgroundcolor

borderwidth=>WIDTH

WidthofborderChoosing'0'willhidetheborder

command=>SCRIPT

ExecutesSCRIPTwheninvoked

cursor=>CURSOR

Mousecursortodisplaywhenmouseinthiswidget

disabledforeground=>CO Foregroundcolorwhenthewidgetisdisabled
LOR
font=>FONTNAME

UseFONTNAMEfortextstyleItisgiveninthisformatFONTNAMESIZESTYLEFor
example,
-font => "fixed 12 bold"

foreground=>COLOR

Foregroundwhenthestateofthewidgetisnormal

Cansetshorizontal(andoptionallyvertical)widgetsize

geometry=>WIDTHxHEI
GHT
height=>VALUE

Setverticalheightofthewidget

image=>IMAGE

Theimagetodisplayinwidget

justify=>JUSTIFICATIO Multilinejustification:left,rightorcenter
N

ForobjectslikescaleandscrollbarMustbehorizontalorvertical(orhorv)
orient=>ORIENTATION
padx=>NUMBER

HorizontalpaddingThespaceontopandbottomofthegivenwidgetForexample,
padx=>5

pady=>NUMBER

VerticalpaddingThisisthespaceoneithersideofthegivenwidgetForexample,
pady=>2

relief=>RELIEF

3DbevelborderRELIEFmustbeflat,groove,raised,ridge,solidorsunkenVery
usefulwhenusingframe

state=>STATE

Setwidgetto:normal,disabledoractive

text=>STRING

Displaytextstring

variable=>VARNAME

DisplaytextvariableIfthewidgetismanipulated,thevalueofthevariablewillchange
automaticallyandifthisvariable'svalueischanged,thewidgetwillchangetoreflectthe
changesinthevariable

underline=>CHAR

WhichcharacterpositioninstringtounderlineThismustbeanumber0forthefirst
character,1forthesecondandsoon

width=>WIDTH

Setshorizontalwidgetsize

wraplength=>LENGTH

Wordwrappingmaximumstringlength

SomeTkCommands
Bind
ThebindcommandassociatesPerlcodewitheventsIfyouwanttodosomethingwhentheuserdoubleclicksaitemin
alistboxorwhenhe/shepressanybutton(sayF1),bindiswhatyouneedLetsbindsomethinginthenextexample
Syntax:
$widget -> bind(<sequence>, Callback);
<sequence>standsforthesequenceofbutton/mousepressesItshouldbegiveninthefollowingpattern
<modifiermodifiertypedetail>Forexample
<ControlAltKeyt>Control+Alt+T
ControlandAltarethemodifiersandKeyisthetypewithtasthedetailSeethenextexampleandyouwillunderstand
#!/usr/local/bin/perl
use Tk;
# Main Window
my $mw = new MainWindow;
my $lab = $mw -> Label(-text=> " The Bind command ",
-font=>"ansi 12 bold") -> pack;
my $lst = $mw -> Listbox() -> pack;
$lst -> insert('end',"Don't double-click this");
$lst -> insert('end',"Don't double-click this either");

$lst -> insert('end',"Don't even think of double-clicking this");


$lst -> insert('end',"You may double-click this");
$lst -> insert('end',"No Negative Nay Nope Get the message?");
#Bind the double click event to the list box
$lst -> bind ('<Double-ButtonPress-1>', sub { double() });
my $all_keys = $mw -> Label(-justify=>"left",
-text=>"Press any of the following
Control+A
Control+Shift+A
Control+Alt+T
Right click
Control+Escape") -> pack;
#Exit when the escape key is pressed
$mw -> bind('<Key-Escape>', sub { exit });
#Shows a helping dialog box when F1 is pressed
$mw -> bind('<Key-F1>',sub { help(); });
#Binds misc keys
$mw -> bind('<Control-Key-a>', sub {
$mw -> messageBox(-message=>"You pressed Control+A, did'nt you?")
});#Control+A
$mw -> bind('<Control-Key-A>', sub {
$mw -> messageBox(-message => "Control+Shift+A, right?");
});#Control+Shift+A
$mw -> bind('<Control-Alt-Key-t>', sub {
$mw -> messageBox(-message => "Control, Alt and T");
});#Control+Alt+T
$mw -> bind('<ButtonPress-3>', sub {
$mw -> messageBox(-message => "The right way to click");
});#Right click
$mw -> bind('<Control-Key-Escape>', sub {
$mw -> messageBox(-message => "You must be a married man
What you pressed remindes married men of what they never will have
- Control or Escape");
});#Control+Escape
MainLoop;
#The helping function
sub help {
$mw -> messageBox(-message=>"Did you ask of help?
You ain't getting any
Ha Ha Ha!");
}
#This happens at double-click
sub double {
$mw -> messageBox(-message=>"You double clicked something
This script is simple - so it won't display what you clicked on
But if you want a sript that is able to do that,
write to me at binnyva\(at\)hotmail\(dot\)com
and I will send you a better script");
}

NowWhat?
Perilousseascrossed,thoughtscorchingdesert,wehavecomehereafterovercomingcountlessdangerstolifeandlimb
Wehavereachedtheendofourquest,theendofourjourneyNowWhat?
NowyouareonyourownYoumuststrivetoachieveexcellenceinthefieldofPerl/TkprogrammingBuybooks,visit
websites,stealcodesDoanythingtoincreaseyourknowledgeonthissubjectThereareanamazingarrayofwebsites
outtherethatwouldsupplyyouwithtutorials,programs,gamesetconPerl/TkGogetthemReadcodeofotherpeople
andstudyfromthemRemember,creativityisgreat,butplagiarismisfaster
ButthemostimportantthingprogramGetthosefingerstyping,makeprogramsinPerl/TkExperimentMake

mistakesCorrectthemThereisnobetterwayoflearningasubjectthanbydoingit
SeereferencesformorelinksonPerl/Tk

Reference
Books
'MasteringPerl/Tk'bySteveLidieandNancyWalshisagoodbookthatteacheshowtocreateGraphicalUser
InterfacesinPerl
LearningPerl/Tk
ProgrammingPerl'byLarryWallisthestandardbookonPerlIfyouconsiderseriousPerlprogramming,thisisa
mustThisisaboutPerlratherthanaboutPerl/Tk
GetMoreBooksonPerl/Tk

Manual
MakeyourselffamiliarwiththemanualthatcomeswithPerlToknowmoreaboutanycommands,sayprint,justtype
perldoc -f printinthecommandpromptThisworksonbothUnixandwindowsmachinesOtherthatthat,Perl
shipswithtonsofHTMLtutorialsthatteacheseverythinginperl

ExternalSites
Perl'sUsenetgroupatcomplangperltkisofgreathelptoanyPerlTkprogrammer
http://wwwperlorg/hasbeenforagestheprimaryresourcesiteformanyperldevelopers
http://learnperlorg/isasitethathasresourcesforbothbeginnersandadvancedperlprogrammers

Appendix
AppendixA:AbouttheAuthor
MynameisBinnyVAIhavebeenprogramminginPerlandTcl/TkforawhilenowbutonlyrecentlyhaveIstarted
programmingwithPerl/TkSoIamnotanexpertinPerl/TkButIhavealreadywrittenatutorialforTcl/TkSoIthought
thatIwilltranslatetheTkpartstoperlandgivetheworldanewPerl/TkprogramSodon'tbeangryifyouseealotof
similaritiesbetweenTcl/TkTutorialandthisPerl/TktutorialIcanplagiarisefrommyself,can'tI?Anyway,all
questions,suggestions,criticismsetccanbedirectedtobinnyva@gmailcomYoucanknowmoreaboutmeatmy
websiteForalltheprogramsthatImadeinPerl,gototheperlpageinmysite
Ifyouhavelikedthistutorial,IhavewroteanothertutorialonTcl/TklanguageCheckitout
IalsowrotetutorialsonCGIPerlandJavaScript

AppendixB:CommonlyMademistakesinPerl/Tk
Thereareafew'irregularities'attheplaceswherePerlandTkmeetTheseplacesareoftenasourceofproblemsfor
newPerl/TkprogrammersHereisalistofmostcommonmistakesmadebynewPerl/TkprogrammersImadequitea
fewofthemmyself
Callbacks

CallingafunctionfromabuttonisalmostalwaystroublefortheinexperiencedAssumethatyoucreatedafunction
calledshowGreeting$button = $mw -> Button(-text=>"Hello",command=>showGreeting);#Won'twork
$button = $mw -> Button(-text=>"Hello",-command=>showGreeting());#Again,won't
work
$button = $mw -> Button(-text=>"Hello",-command=>&showGreeting);#Willnotwork
Thisistheporperwayofdoingit
$button = $mw -> Button(-text=>"Hello",-command=>\&showGreeting);#Finally
Somethingthatworks
$button = $mw -> Button(-text=>"Hello",-command=>sub { showGreeting(); } );#
Anothermethodofdoingit
Variables
Thishasasimilareffectastheaboveproblem
$entry = $mw -> Entry(-textvariable=>$var);#Thisisnottherightway
$entry = $mw -> Entry(-textvariable=>\$var);#Correctway
Usingqw//
Don'tuseawhitespaceinsideavalueifyouareusingtheqw//methodtoconfigureoptionsSeebelowformoredetails

AppendixC:Tcl/TkAndPerl/Tk
IfyouaremoresquintedwiththeTcl/Tk'swayofdoingit,youwillbehappytoknowthatthereisawayofgivingthe
optionsintheTcl/Tkstyle
$label = $mw -> Label(qw/-text Hello -font courierfont -relief raised/) ->
pack();
qwfunctionwillsplitthegivenstringatwhitespaceItcanbeunderstoodasbeingroughlyequivalentto:
split(' ', q/STRING/);
SothenospaceisallowedinsidevaluesifyouareusingthisForexample,thefollowinglinewillcreateanerror
$label = $mw -> Label(qw/-text "Hello World" -font courierfont -relief raised/)
-> pack();
Evenusingquotes(")willgiveunexpectedresults
$label = $mw -> Label(qw/-text "Hello" -font courierfont -relief "raised"/) ->
pack();

AppendixD:Codes
Almostalltheprogramsinthetutorialareavailableinazippedformatfordownload

AppendixE:FeedBacks
Howdoyoulikethistutorial?Pensomecommentsbelow
Ifyouhaveanyquestionssendmeanemailatbinnyva@gmailcomIfyouleaveaquestionintheabovefeedbackform,
besuretogiveyouemailaddressifyouwantmetorespond

AppendixF:Comments
Index
Anonymousat11Mar,200804:26

Hi
everytimeitrytoaccessperltkmoduleitgivessegmentationfaultiusedaptgettoinstallperlandperltkmodules

Anonymousat01Jun,200810:30
tryinstallingthemwithCMA

Introduction
AnshumanAtreat26Feb,200708:41
Hi,
IhavejustfinishedagreattoolwithmanycommandlineoptionsItalsohasabasicCLIbaseduserinterfacetomakeit
interactive
IhappentoaowntheO'Rielly"Perl/Tk"thatIboughtforastealafewyearsago,andamconsideringaddingaGUIto
mytoolSoIdownloadedthePerl/TksourcecodefromCPANandfailedtocompileitusinggcconSolarisHowever,it
compiledfineonmyLinuxbox
ItriedoutafewcodesnippetsandthesearemyfirstimpressionsaboutPerl/Tk:
1Yes,it'spowerfulenoughtoprovideacoolfrontendtomytool
2Thecodingseemsprettystraightforward,thoughrepeatativeandmonotonous(withlotsoftrialanderroriterations)
3Theenduser,howeverwouldneedPerl/Tkinstalledonhis/herboxtoabletorunmyPerl/Tk,whichisNOTshipped
bydefaultHowdoIconvincehim/hertospendagoodpartofanhourtogetPerl/Tkinstalled,sothathecanusemy
tool!?It'dbeeasierforhim/hertousethe(ample)commandlineoptionsIgive,orusetherudimentarytextbased
interface
Somyquestion:IfIspendagoodpartofamonthwritingaPerl/Tkinterface,whatarethechancesthatanaverage(not
aprogrammer/admin)user/operatorgetstouseit?
Thanks!

BinnyVAat27Feb,200705:04
Tkinterface,unfortunately,looksreallyoutdatedinlinuxsystemsHowever,inwindowssystemstheylookgreatIfto
wantcoollookinginterfacesinLinux,trysomethinglikeGtkforperl
MyadviceistoprovidetheGUIalongwiththeapplicationbutafterseparatingtheapplicationfromtheGUITheapp
shouldworkwithouttheGUIifthatishowtheuserwantsitTheGUIwillbeavalueadd

Marianoat27Mar,200705:22
IftheuseriscurrentlyusingaWindowsterminalyoucouldgenerateanexewithyourappinwichyoucanincludeall
theusedlibraries(ieTk)
Ifnot,itmeansitisveryeasytoinstallthemodule

Anonymousat14Mar,200808:37
UsePerl2Exetocompileitintoaexe,itautomaticallyincludesthePerl/Tkbinaries(Ifyouronwindows,otherwise,lul
linuxfails)Useserialswstofindaserialforperl2exe

purnachanderat05Jul,200708:08
Hi,
I'mtryingtoaddGUItomytoolSoistartedlearningPerl/TkmoduleCanyoutellmewhereIcangetdocumentation
fordifferentvaluesofanoption

Foreg,Theoption"background"isusedtosetthebackgroundcolorIknowhowtosetmybackgroundtocommon
colorslike,green,black,etcHowever,ifI'dliketochoosemyowncolorfromRGBHowcanIdoit?
Similarly,ifineedtoknowvariousvaluesavailableforanoption,whereshouldisearchfordocumentation

BinnyVAat05Jul,200711:07
JustsearchthenetyouwillgetPerl/TkDocswithoutmuchdifficultyForinstance
Perl/TkDocumentation

Anonymousat30Aug,200711:58
IdonotseetheanswerinthatdocumentationI"mlookingforthepropersyntaxtospecifythecolorinRGBinsteadof
acolornamepurnachander,didyoueverfindit?

balajiat30Jul,200709:46
hi,
iscriptingatoolforvlsidesignusingperlButidontknowhowtomaketheguiforitCanuelaboratelytellmewatar
allstepstobecarriedout

Anonymousat09Aug,200703:21
ifiusethismethodforinstallingTk
perlMCPANeshell
cpan>installBundle::CPAN
cpan>reloadcpan
cpan>installTk
iamfindingthiserror
FetchingwithLWP:
wwwperlorg/CPAN/authors/id/N/NI/NIS/Tk804027targz
LWPfailedwithcode[500]message[readtimeout]
cansomebodyhelpmepls!!!!!

BinnyVAat09Aug,200707:04
YourbestbetisjusttotryagainIthinkitisatemporaryserverissue

senthilat04Sep,200706:10
hi,
iamsenthilineedacodeofperltkineedtogetainputfromuserusingtheoneinputlikevisualbasicsogetvalueto
assigntheonevariable
like"$input=ccnb"
ccnbisgetfromuser
senthil_v@newgenimagingcom

BinnyVAat04Sep,200709:11
ThedetailsareavailableintheEntrypage

aflexoat11Dec,200704:07
Greatsamplesintutorial!ThesejusthelpedmetounderstandthewholethingaboutPerl/TKprogramming))

dswat18Dec,200708:50
ThisinterfacedoesnotlookoutdatedIfyouarelookingforsomethingmorepolished,thenIsuggestyouwritea
tutorialaboutusingQTOldschoolistheonlyschool:)

BinnyVAat18Dec,200711:08
Unfortunately,youarerightinthecaseofLinuxTkinterfaceinLinuxisjusthorribleButitlooksrathergoodin
WindowsPlusIhavenotlookedatQTyetIhavelearnedabitofGtkbutnowhereenoughtowriteatutorial

PhillCat10Jan,200807:21
First,thanksforagreattutorialusingPerlTKYourstyleandexamplesworkformeverywell
I'membarkingonmyfirstPerlGUIprogrammingexperienceAfterinvestigatinganumberofoptionssuchatGTK2
andwxWindows,IthinkTkappealstomemostWhilethePerlTkGUIlookandfeelmaybealittleoutdated,Ilikethe
syntaxusedtocreateitIespeciallylikethegridpackagingsystem
I'vebeenreadingabouttheTcl::TkmodulecurrentlyavailableinCPANItseemsthatithassomeadvantagesover
PerlTK,specificallyspeedandtheabilitytousethelatestTcl/Tk85widgetssuchasTileItalsoappearstosupport
PerlTKsyntax,butofcoursetherearesomedifferences
Iwaswonderingifyou'dconsideratutorialhighlightingtheTcl::TkmodulevsPerlTkdifferences,andespecially
whichwidgetsareincludedinTcl:TkbydefaultandhowtocallexternalTclwidgetsInfact,maybejustasinglepage
explainingthesedifferencesmightbereallyuseful
Regards,
Phill

BinnyVAat13Jan,200807:21
I'lllookintoitbutchancesarethatIwillnotbeabletodothisstudyCurrentlyIaminWebDevelopmentIhavenot
beenactiveattheTkfrontSo,myknowledgeaboutthosesystemsareabitoutdatedAnyway,thanksforthesuggestion
Iwilllookintoit

Anonymousat27Feb,200804:58
assigningavariabletobackgroundsandthingslikethat
textvariableisfortext,butIcannotfindasimilarentryforframesoranythingelseoutsideoftextinalabel
Igetamessagethatsaysunknowncolorname"SCALAR(0x18a3f6c)"ifIusecodesimilarto$frame=$mw>Frame(
background=>\$variable)>pack();
butifIuse$frame=$mw>Frame(background=>$variable)>pack();withouttheslashthewidgetisassignedtothe
onecolorpermanently
thisisasignificantproblemtomeandIwouldappreciatesomeoneelsetryingtosolvethis,becauseIhavebeenunable
tofindDocsmyselftoassistme

Chanioat03Mar,200805:20
Iappreciateverymuchyourgreatandhonestwork!
Thiscompletetutorialisaveryhelpfultoolforboth:theusersandtheperl/Tkcommunity
Wouldn'titsuitbetterifyoursitehadawikistyle?
Iimagineperldocspublishedonlineinawikifashion,allfullofhyperlinks
THXS!Haveaniceyear!
Alberto(Argentina)

Anonymousat14Mar,200806:23
FinallyfiguredouthowtospecifyrgbcolorsforwidgetsPostingithereincaseanybodyelseislooking
Puta#infrontofthe6digitrgbcodeandencloseitwithsinglequotes
Ex

background=>'#ff0000'

KumarPat03Apr,200806:45
IhaveanassignmenttocreateaGUI,whichshouldbeabletoparsetheMPEGVideoBitStreamandshowusvarious
properties/semanticsoftheunderlyingvideoIsperl/TKtherightchoicefordevelopingsuchapplication?

Jefffreyat04Apr,200810:35
I'vestartedwritingadatabaseandpointofsalefrontendformydiveshopI'musingperlbecauseit'stheonlylanguage
I'msomewhatfluentinIhaveusedTkbeforebutnotGtk2Cananyonetellmeifthereisenoughinfoouttheretoget
thehangofGtk2fairlyquicklyoristherealearningcurve

Chanioat10Apr,200808:04
IfsomeonewantstogetamoreVBlikeresultwithTkyoumightwanttousethefree:ZoozGUIbuilder
ItisnotbetterthandoingitallbycodingItisjustanotherwayofcomplementingyourknowledgeofPerlTkAnd,
perhaps,learningsomethingnew!

Rathnakarat21Apr,200809:41
TogetGuiyoucanuseperl/Tkmoduleswhichwouldgivemoreflexibility
IfounditveryusefulRefertotheexamplesinthesitetogetabetterpicture

Anonymousat07May,200807:47
AwonderfulltutorialthathelpedmealotandIstillkeepforreferences!
MyThanks

Anonymousat20May,200812:51
ThanksBinny,
YouhavedoneagreatjobontheTktutorialIamactuallylookingforhelponWindows(active_state)basedTksIn
particularutf8supportforTksusingforeignlanguagefontssuchasRussian,Mongolian,ChineseDoyouknow
whetherTkswillsupportutf8?
Vanilla

HelloWorld
Anonymousat30Jan,200705:34
couldn'tconnecttodisplay":0"at/opt/perl/lib/site_perl/582/PARISC11thr
eadmulti/Tk/MainWindowpmline55
MainWindow>new()atwelcomeplline5

BinnyVAat31Jan,200704:31
IhaveneverseenthiserrorbutdoyouhaveXserverrunning?TkneedsaGUIdisplay

Anonymousat17Apr,200712:16
youneedtosetyourdisplayenvironmentvariable,andthenalsoifyouaretelnetingandhavefurtherproblems'xhost
+'fromtheoriginatingmachine

fredat28Apr,200704:54
Hello,
WhenIrunthehelloexampleonmywinxpbox
itopensacommandpromptItstaysopenuntil

Iclosetheexample
IsthisthewayallPTKprogramswork?
Thanks

BinnyVAat28Apr,200705:38
YesthatshowtheyworkDon'tworryaboutit

Jaysonat19Jun,200703:52
ldso1:/usr/local/bin/perl:fatal:libctso:openfailed:Nosuchfileordirectory
Pleasehelp

BinnyVAat19Jun,200709:31
ThereissomeissuewithyourperlinstallationsomelibrariesaremissingTrydownloadingperlandinstallingit

AMPat03Aug,200708:56
Probablynotaproblemw/installation,Perlismostlikelyin/usr/bin/perlinsteadAlltheLinuxdistributionsIhave
workedonhaveitinthislocation

kittuat21Jun,200708:57
HI
Friends
ihavesomeissuesplshelpmeonthisactuallycgi/peralwithNT40environmentismovingbyLinuxany
disadvantagesandsuggestifthatisreengineeringwithjava,linuxandgivemesomepointsandpresentlyexisting
systemhaving5003wanttochangeto583soanydeprcciationididnotfindanyproblemsplshelponthatandwith
linuxhowtodeploycgi/pearlprograms

Jonathanat03Aug,200703:07
Kittu,CongratulationsonyourpostIhaveneverreadanythingmorecompletelyincomprehensibleplskeppupthe
goodwerkuntrtaneme

Anonymousat21Sep,200710:59
ThanksforthetutorialBinnyIt'sverygood!

Anonymousat24Nov,200708:49
VeryclearandunderstandableNicetutorialThankYoutotheauthor

OddChildat09May,200808:29
thankyouforputtingthistogether,itwasmosthelpful

Anonymousat21May,200807:00
thislineisveryslow:
$mw>messageBox(message=>"Goodbye");
Isthatsupposedtobe?Orjustmyenvironmentissue?
Thanks

Anonymousat21May,200807:02
MessageboxlineisveryslowIsthatsupposedtobe?Oritismyenvironmentissue?
Thanks

Sidat21May,200809:01
NewtopTk,pullingperloutofcoldstorageYourtutorialishelpfulThankyou

Widget1
Anonymousat31Jul,200702:49
Theexampleabovewiththefunctionpush_buttonisnotshowingthetext"whatever"Alsoifiusethecommanduse
strict,howdoiwritethebaretextwhatever

BinnyVAat01Aug,200706:19
NoyoumisunderstoodmeThat'whatever'isnottheoutputImeantyoucanputthecodeyouwantinitsplaceOn
hindsight,IthinkIshouldhavecommentedit

Anonymousat31Jul,200704:31
Ithinkthefunctionbody(sub)shouldbewritteninsideMainLoopitselfIhadpostedthesamequestionandIthinkthe
answeristhisdescription

Jackat01Aug,200703:17
Isthereacommandtotogglethevisibilityofawidget?preferablylabelandentrywidgets

BinnyVAat01Aug,200706:28
Thereisthedestroy()functionthatwilldeleteawidget
my$lab=$mw>Label(text=>"Entername:")>pack();
$lab>destroy();

ANGIEat08Sep,200704:52
YOURCODEISSOGREATYOUSHOULDSTARTAPAIDCERTIFICATIONCOURSE
YOUROCK,MAN!

Anonymousat21Sep,200711:38
AstheysayinShakespeare'stime,"YoudaManHomeSlice"!Thanksforthis!

Anonymousat21Sep,200711:43
Doyouhaveanexampleofabuttonthatthe"state"changesfrom"disabled"to"normal"aftersomeevent?
Thefollowingdidn'tworkforme
my$Enable_button="disable";
$mw>>Button(text=>"PushMe",
command=>\&push_button);
state=>$Enable_button,
or
state=>\$Enable_button,
$but>pack();
then,later
$Enable_button="normal";

BinnyVAat22Sep,200701:15
Therightwaytodothisis
my$button=$wm>Button(text=>"PushMe",command=>\&push_button,state=>"normal");
Later

$button>configure(state=>'disabled');

PaulRat24Sep,200707:11
BinnyVA
That'sitThanksforyourhelp

SibuNLat11Mar,200812:59
Binny,
WhenIrunaperl/TKsimplehelloworldapplicationbydoubleclickingonit
underwindowsxp,
acommandwindowalsoopenedalongwiththehelloworldapplicationwindow
Howtoavoidorhidethecommandwindowfromappearingonscreen
Thanksinadvance,
SibuNL

BinnyVAat11Mar,200803:53
Idon'tthinkyoucandoanythingaboutthat

Kerbiquetat18Mar,200804:07
Hi,
Checkthisexample,takenfromthePerlCookbookeditedbyO'Reilly:wwworeillycom/catalog/perlckbk2/tochtml
Thewindowsconsolepopsupbydiseappearimmediatly

Kerbiquetat18Mar,200806:33
YouhavewrittenaPerlprogramfortheWindowsportofPerlandTk,butyougetaDOSshellwindoweverytimeyou
startyourprogram
Addthistothestartofyourprogram:
BEGIN{
if($^Oeq'MSWin32'){
requireWin32::Console;
Win32::Console::Free();
}
}
TheWin32::ConsolemoduleletsyoucontroltheterminalwindowthatlaunchedyourprogramAllyouneedtodois
closethatwindow(orFreeitin,inthepeculiarparlanceoftheWindowsAPI)andvoilanopeskyDOSshellwindow
ThedocumentationfortheWin32::Consolemodule,whichisincludedwithdistributionsofPerldestinedforMicrosoft
systems

Anonymousat20Mar,200809:21
Entry()takesa1lineinputwattodoifiwantttocaptureatextareaasinput&manipulaateit?

BinnyVAat21Mar,200803:59
ItsinthenextpageTextwidget

Anonymousat06May,200801:29
canyoupleasetellmehowcanideleteormakethescrolledlistboxinvisibleinthemainwindow?
Iamdeveloping1applicationinTK(VTcl)

Anonymousat09May,200802:37
HiBinny,
Ihaveasubmainp(),whichrunsinloopandmaytakelessthanasecondorfewminutessometimes,Iwanttoexit
fromtheprogrambeforemainp()finishesIhavethefollowingcodecouldyoupleasesuggestmehowtoachievethis?
my$print=$right1>Button(text=>'BuildIndex',
command=>\&mainp)>
grid(qw/row7column1stickyse/);
my$exit=$right1>Button(text=>'Exit',
command=>[$mw=>'destroy'])>
grid(qw/row7column2stickysw/);

Anonymousat19May,200801:02
Hi,
Iamtryingtocreateanddeletewidgetslabel&entrydynamicallyIamabletocreatewidgetsbutunabletodeletethe
specifiedrangeofwidgetsIamusingGridmanagerCouldyoupleasehelpmeoutforthesame?

Anonymousat12Jun,200809:11
Ifyouexecutetheperlscriptwithwperlexeinsteadofperl,nocommandconsolewillbedisplayedIfyoueditthe
actionsforthepltypeyoucanmakeaRunwithwperl

Widget2
Anonymousat01Apr,200703:25
Inthetextareaintheexampleabovethescrollbaronthexaxisdoesn'tevergetusedbecausethetextalwaysstartsa
newlineinsteadofgoingoffthesideWhatcanidoaboutthis?

BinnyVAat01Apr,200709:27
ThisisbecausetheTextwidgetdefaultstowrappingTodisablethisbehaviour,justusethiscode
my $txt = $textarea -> Text(-width=>40, -height=>10,-wrap=>'none');
See"-wrap=>'none'"thatwilldisablethewrapTheotheroptionsforwrapare'word'and'char'

Anonymousat01Apr,200711:36
thanks!

Anonymousat01Apr,200711:36
thanks!

Anonymousat01Apr,200701:45
Whenitriedthisitdidn'tworkandsaid:
Tk::Error:OddnumberofargstoTk::Text>new()
Tkcallbackfor
Tkcallbackforframe
Tkcallbackforframe1
Tk::Widget::newat/usr/lib/perl5/vendor_perl/588/i586linuxthreadmulti/Tk/Widgetpmline164
Tk::Widget::__ANON__at/usr/lib/perl5/vendor_perl/588/i586linuxthreadmulti/Tk/Widgetpmline256
OddnumberofargstoTk::Text>new()
at(pathname)/scrollbar_and_grid_tutline14
whatdoesitmeanandhowcanifixit?

BinnyVAat02Apr,200706:02
PleaseprovidetheexactcodeyouusedAlso,couldyouemailittome?Thatwouldbebetterthanusingthiscomment
systemMyemailisbinnyva,gmail

Anonymousat02Apr,200707:49
Hi,
Couldyoupleasetellhowtopositionthe"textmessge"inthecenterofthewindowaswellaspositionthe"Quit"
buttonThanks

BinnyVAat02Apr,200711:44
IamnotsureIunderstandyourquestionCouldyoujustcreateasmallimage(usingMSPaintorsomething)onhow
youwantthelayoutandsendittomy?ThatwayIcanunderstandwhatyouneedMyemailisbinnyva,gmail

Anonymousat04Apr,200705:42
Hi,
Isthereanywayofcentrallyaligningtextinsideatextwigit?

BinnyVAat04Apr,200706:28
Trythiscode
my $lab = $mw -> Label(-text=>"Hello",-anchor=>"center") -> pack();

Anonymousat06Apr,200709:47
Sorry,imeantinatextwigit,notalabelwigit
Iwantedcentrallyalignedtextspanningmorethatonelinewithadifferentrelieftoalabel
pleasehelp!

Anonymousat04Apr,200706:31
Hi,
Isthereanywayofcentrallyaligningtextinsideatextwigit?

Anonymousat04Apr,200706:32
soz

Anonymousat04Apr,200706:43
howdoyoumakeatextwigitreadonly?

Amitat05Apr,200709:28
IsthereanywaytolocktheTextFieldSotatonlycontentsaredisplayednonecanedit???

BinnyVAat05Apr,200710:17
Tryusing-state=>'disabled'Ifyouhaveotherdoubtslikethis,takealookattheTkreferencemanualEvenif
themanualisforTcl/Tk,itcanbeusedforPerl/Tkaswell
TkManual

Anonymousat06Apr,200707:58
Ifthestateisdisabledisitstillpossibletoeditthecontentsfromwithintheprogram?

BinnyVAat08Apr,200705:52
Noitisnotpossible

Venugopalat04May,200704:46
Hi,
IhavearequirementtolistthecontentsofafileinaGUI,withtheoptionstomakeaselection(oneormore)fromthe
listandstoretheselecteditemstoanothervariableoranotherfileIhaveusedlist,scrollbarandcouldlistthecontents

ofthefileButhowcouldIaddtheselectionfeature?HereismycodeCouldyoupleasehelpmehowcouldIachieve
this
$list=`type$file`;
my$mw=newMainWindow;#MainWindow
$mw>title("Output");
$mw>resizable(0,0);
my$textarea=$mw>Frame();#CreatingAnotherFrame
my$txt=$textarea>Text();
my$srl_y=$textarea>Scrollbar(orient=>'v',command=>[yview=>$txt]);
my$srl_x=$textarea>Scrollbar(orient=>'h',command=>[xview=>$txt]);
$txt>configure(yscrollcommand=>['set',$srl_y],
xscrollcommand=>['set',$srl_x]);
$txt>grid(row=>1,column=>1);
$srl_y>grid(row=>1,column=>2,sticky=>"ns");
$srl_x>grid(row=>2,column=>1,sticky=>"ew");
$textarea>grid(row=>5,column=>1,columnspan=>2);
$txt>insert('end',"$list");
MainLoop;
ThanksinAdvance

Anonymousat10Jul,200709:11
Hi,
I'mtryingtosetscrollbarsforMainwindowHowever,I'mfailingtodoitCanyoupleasehintmehowtogothrough
this?

Tcl/Tkprogrammerat06Oct,200705:20
Howdoyouautomaticallysendtextdatatoatextwidget?Forexample,tailf/var/log/messagesI'mworkingonareal
timestatusscriptforthejobManythanksinadvance,Binny?

Anonymousat14Apr,200810:08
ThisisthemostexcellenttutorialIsthereanywayIcangetacopyofthistouselocally,offline?Thankyou

Anonymousat11Jun,200802:43
Fantastictutorial,IusedyourTcl/TkoneaswellandfounditveryhelpfulIdothinkthoughthatscrollbarsarethemost
difficultsectiontounderstandforabeginner,perhapsyoucouldspendabitmoretimeonthem?Justathought:)

Widget5
Anonymousat23Apr,200709:54
whatisatearoffentry?

Anonymousat17Jul,200705:36
It'sapartofamenuwhereyoucanclickalittlebutton,andthen,youcanclickonanythinginthelittlemenuwhile
clickingsomethingelseinthebigmenu

Gregat23May,200712:28
Doyouknowhowtochangethebackgroundcolorfortheseparator?

I'vetriedusingthefollowingcodebutithasnoaffect:
$file->separator( -background=> 'white' );
Iwouldbeverythankfulforanyhelpyoucouldgive!

ELJONTOat19Jun,200712:10
Canyouusethemenuthatyouhaveusedintheaboveexampleandchangeitsbackgroundandforegroundcolours?Or
doihavetomakemyownmenu?

jackat31Jul,200711:37
howdoyoucreateanoptionthathasmorethanoneword?

Anonymousat30Apr,200808:11
my$curlist=$mw>Optionmenu(options=>["firstoption","secondoption"],variable=>\$var)>pack();
Dontusetheqwfunction

Widget6
Anonymousat14Feb,200811:10
WhenIfirstreadthispage,IthoughtyouweredismissingCanvaswidgetsasimpotent
Butfurtherreadingsuggestsyoumeant"important",astheycertainlyseemtohavesomepowerWhichisit?
StuartDoty

BinnyVAat16Feb,200812:48
Mybaditsfixednow

Anonymousat27May,200811:39
hi,
iwanttomakearealtimeguiwhichupdatesitselfbutaddingelementstothecanvasordeletingthem
CanyoubemoreillustrativeusingCanvasandhowcaniintegrateitwithanenvironmentwhichupdatesitself
periodically
Thanks

GeometryManagement
Isthereanywayto'ungrid'something?
WhenIclickaradiobuttonIwantoneframetobereplacedwithanotherprepreparedframe
Thanks

decat10Sep,200708:04
$widget>gridForget;

Anonymousat06Jul,200711:24
WhenIrunthisCodeonmySolarisBoxwhichhas588perlInsatlledIgetaCoreDUMP
AnyReasonWhy?
#!/usr/local/bin/perl
useTk;

usestrict;
#MainWindow
my$mw=newMainWindow;
my$response=$mw>messageBox(message=>"Reallyquit?",
type=>'yesno',icon=>'question');
if($responseeq"yes"){
exit
}
else{
$mw>messageBox(type=>"ok",
message=>"Iknowyoulikethisapplication!");
}
MainLoop;
TheStacktraceisgivenbelow:
$pstackcore
core'core'of28384:/usr/local/bin/perl/temp
ff1428c0t_delete(43261c,ff1bc008,ff1c27cc,ff1c284c,ff1c2848,0)+68
ff141f50_malloc_unlocked(68,43261c,ff1bc008,68,43261c,0)+18c
ff141da8malloc(68,0,20,8,215e4,fee9b938)+20
feea624c_XEnq(0,ffbeebc4,14e2c8,ffbeeb5c,14e2c8,20)+28
fee9ccdc_XReply(14e2c8,39,0,1,39,14e2c8)+498
feea7088XInternAtom(0,ff04b2fc,0,14e2c8,a5c46890,40)+bc
fefd7474Tk_InternAtom(38a4f0,ff04b2fc,fefcac28,ff031240,1a8e0,1)+4c
ff0312b8UpdateWmProtocols(3f67b0,2c00,153a,1400,ff05c30c,38a5e8)+e8
ff02addcTkWmMapWindow(38a4f0,ff067160,0,38a5e8,ff05c30c,0)+194
ff03703cTk_MapWindow(38a4f0,0,12634,ff1fc910,ff20eda0,38002)+3c
fefed014MapFrame(38a6d8,32c8,6f354,ff1f44f4,ff05c30c,3000)+68
ff1fde8cTclServiceIdle(0,ff1fed8c,0,1,377d30,388828)+98
ff1fc910Tcl_DoOneEvent(22,0,12634,ff3cdf18,ff20eda0,0)+1b0
fefecfe4MapFrame(370770,32c8,6f354,ff1fd5b0,ff05c30c,3000)+38
ff1fde8cTclServiceIdle(0,ff1fed8c,0,0,377d30,36ab80)+98
ff1fc910Tcl_DoOneEvent(22,0,12634,fefb451c,ff20eda0,0)+1b0
fefe261cTk_UpdateObjCmd(2e9408,22a8f4,2,ff07532c,20,32c8)+90
fefba8b0Call_Tk(13984c,2,226514,fefe258c,1397a8,1396f0)+314
fefbd294XSTkCommand(2585a8,1,fefe258c,2,226514,0)+158
fefbd334XStoTclCmd(3400,32fc,4,226510,ff05c30c,1398a0)+90
00096a18Perl_pp_entersub(1,80,2585a8,139400,226518,247918)+664
0008cfacPerl_runops_standard(24e230,136c00,132c00,0,0,8d044)+4c
00028dd8S_run_body(0,ffbeef40,8,139800,139800,28ed58)+164
00028accperl_run(139a60,139400,139400,139e90,139e90,137000)+240
00024f6cmain(2,ffbef4fc,132c00,139800,136c00,139800)+a4
TheTkVersioninstalledis804027

Nirajat01Sep,200702:47
howtorunaperlscriptinGUI
IhaveacodefortranscribingaDNAintoaRNAwritteninperlscriptbuthowshouldigetitsoutputinGUIlayout?
pleasereplysoon

Anonymousat09Dec,200709:03
MydoubtisabouthowtoimplementresetinPerltkIhavetorefreshthevaluesstoredfromtheentrybyusingget()and
againtakethenewvaluessocaniusethesamewindowforthatanduserefreshbutton??Replyme

NowWhat?
Anonymousat15Jan,200701:08
Hi,
IamjuststartingtolearnPerl/PerlTKsoIgoogledthistopic
andfoundyourtutorialwebsiteonthissubjectIamjustfinished
thetutorialandfoundtobeveryhelpfulforanewbielikeme
Thankyourforprovidingthistutorialandforsharingyourexpertise
AlsoIwillfollowyoursuggestion"Thereisnobetterwayoflearningasubjectthanbydoingit"
Thanks,
Ethan

Anonymousat08Feb,200704:15
Andthehumourkeepsonegoingthroughit!
Thanksfortakingthetimetoputittogether!

gobbleat03Apr,200703:17
NicetutorialVeryhelpful

Giulioat23Apr,200703:06
Verygoodjob!
Thankalot
Giulio
Ifit'spossiblefitwithmoreexamples!;D

Aryanat29May,200712:20
GreatWork:)
Regards
Aryan

Anonymousat29May,200701:27
Goodtutorial,ihavelearnedlotsaboutTK

Anonymousat07Jun,200706:01
Thankyou
Ireallyneededthis

Anonymousat10Jul,200710:58
reallyausefullelearningforanewbieinperl/tk
hatsoffforkeepupthegoodworkgoing
thanksalotforthetutorial!!!!!!!!

Anonymousat13Jul,200702:59
ThankyouverymuchforputtingthistutorialtogetherItwasextermelyhelpfultome

Jonathanat01Aug,200701:59
ThanksforpublishingthistutorialIthasbeenagreathelp;yourkarmaexplodes

Anonymousat15Aug,200706:07
ThankyouverymuchItwasreallyhelpful

RajasekarVat28Sep,200701:39
IfoundthissiteveryusefulItsgreataplatfarmforbeginnerstostartwith
moreexamplescouldmakeinmorebetterHatsoffforgreatwork
Regards,
RajasekarV

Rajaat28Sep,200701:41
Hatsoffforyourgreatwork

JZat30Sep,200705:47
bincoyou'rethegreatestwithyouexpertiseinbothTCL/TkandPerl/TkAndyourtutorialisexemplarywork!You
reallyknowhowtoconveycomplexconceptsclearlytothereaderMany,manykudostoyou!

BinnyVAat30Sep,200707:06
Thankseveryone

DanielWilsonat06Oct,200710:59
Greattutorialhelpedmeoutloads:)

LeRoiat10Jan,200804:53
VerynicetutorialThanks!!!!

Anonymousat03Feb,200809:15
HiBinny,
Iamaperl/TknewbieYoursitewasagreathelpThanksCanyoupointouttomeastohowmyapplicationcanaccept
multilineformattedtextualinputfromtheuser?(tosaveittoanexternalfile)Theapplicationhastotowaitontheuser
inputandthenproceedIjustcantseemtogetmyheadaroundit
Thanksalotagainforthetipshere:)

BinnyVAat04Feb,200808:24
TryusingtheTextwidget

Anonymousat14Feb,200811:45
Veryusefultutorialfonewbie
Helpedmegetintoafasttrackprogramming!

Anonymousat04Mar,200806:13
Veryhelpful!thanks

Anonymousat12Apr,200804:01
ThisisagreattutorialI'mreallyhappythatIfoundthis
Thanks!

Anonymousat22May,200809:50
Excellentperl/tktutorialIlovedit5startawardtoyou

Bobat11Jun,200803:14
Hi!

Thisisasuperbtutorialonperl/tk
Manythanksfortakingthetimetoputittogether
Bestregards
Bob

Appendix
Anonymousat19Apr,200705:48
ThisisanexcellenttutorialItgivesyoualltheinformationyouneedtostartwritingGUIprograms,andgivesyou
informationandweretogoandtogetmore

Laurenceat12Jul,200712:32
Thankyousomuchforthistutorial,ithashelpedmeloads
Keepupthegoodwork

Pankajat09Aug,200712:12
QuiteinformativeGotalltheinformationineededasabeginner
Thanks

MariaJat16Aug,200706:24
Ifindthistutorialvery,veryhelpfulThanksalotforyourclear,wellstructuredexplanationandgreatexamples

Markat24Aug,200711:54
Iagreeexcellentstartingpoint,shortandtothepointMuchbetterthanthebaskinmyownglorytypesthatfrequenta
lotofthelinuxpostsites

Dougat25Sep,200712:28
Iagreewiththeothers,thisisanExcellenttutorial!ThanksforsettingitupIthelpedmetoquicklygetbackintoshape
workingwithtkafterabreakof10yearsIjustwishtheauthorsofthepublishedbooksfollowedyourwritingstyleof
clearexamples!
Keepupthefantasticwork!

Anonymousat29Nov,200710:06
ThistutorialwasreallyofgreathelptomeasiwasabegginnerIfwehavetwolabelshowcanthesecondlabelbe
printedinthenextlinebyusingpackgeometrymanager(iusedframalso)IcouldnotgetthatoptionByusinggridi
wasabletodothisHopeyouwillreplymeassoonaspossibleThankyou

BinnyVAat30Nov,200702:00
pack first_label
pack second_label

Thatshoulddoit

AvidanZhangat22Jan,200812:28
Veryhelpfultutorial!EasyfornewcomerstomakefirststepinTKunderPERL

Thankyouverymuch!

You might also like