Upload
chituiniyan7541
View
34
Download
0
Embed Size (px)
DESCRIPTION
good
Citation preview
Perl/TkTutorialCreateGUIwithPerl'sTkModule
Introduction ......................................................................................................................................................................... 2Applications ................................................................................................................................................................... 2Philosophy ...................................................................................................................................................................... 2Perl/TkRequirements ..................................................................................................................................................... 3Installing/UsingPerl ....................................................................................................................................................... 3
HelloWorld ......................................................................................................................................................................... 3Widgets1:Button,Entry,Label ........................................................................................................................................ 5
Button ............................................................................................................................................................................. 6Entry ............................................................................................................................................................................... 6Label ............................................................................................................................................................................... 7
Widgets2:Frame,Text,Scrollbar,Scale ........................................................................................................................... 8Frame ............................................................................................................................................................................. 8Text ................................................................................................................................................................................. 8Scrollbar ......................................................................................................................................................................... 9Scale ............................................................................................................................................................................. 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
IntroductionPerl/Tk(alsoknownaspTk)isacollectionofmodulesandcodethatattemptstowedtheeasilyconfiguredTk8widgettoolkittothepowerfullexigraphic,dynamicmemory,I/O,andobjectorientedcapabilitiesofPerl5Inotherwords,itisaninterpretedscriptinglanguageformakingwidgetsandprogramswithGraphicalUserInterfaces(GUI)
PerlorPracticalExtractionandReportLanguageisdescribedbyLarryWall,Perl'sauthor,asfollows:"Perlisaninterpretedlanguageoptimizedforscanningarbitrarytextfiles,extractinginformationfromthosetextfiles,andprintingreportsbasedonthatinformationIt'salsoagoodlanguageforanysystemmanagementtasksThelanguageisintendedtobepractical(easytouse,efficient,complete)ratherthanbeautiful(tiny,elegant,minimal)"Theperlintromanpagehasthistosay
Perlisageneralpurposeprogramminglanguageoriginallydevelopedfortextmanipulationandnowusedforawiderangeoftasksincludingsystemadministration,webdevelopment,networkprogramming,GUIdevelopment,andmore
Tk,theextension(ormodule)thatmakesGUIprogramminginperlpossible,istakenfromTcl/TkTcl(ToolCommandLanguage)andTk(ToolKit)wascreatedbyProfessorJohnOusterhoutoftheUniversityofCalifornia,BerkeleyTclisascriptinglanguagethatrunsonWindows,UNIXandMacintoshplatformsTkisastandardaddontoTclthatprovidescommandstoquicklyandeasilycreateuserinterfacesLateronTkwasusedbyalotofotherscriptinglanguageslikePerl,Python,Rubyetc
ApplicationsPerlhasbeenusedsincetheearlydaysofthewebtowriteCGIscripts,andisnowacomponentofthepopularLAMP(Linux/Apache/MySQL/Perl)platformforwebdevelopmentPerlhasbeencalled"thegluethatholdsthewebtogether"LargesystemswritteninPerlincludeSlashdot,andearlyimplementationsofWikipediaandPHP
Perlfindsmanyapplicationsasagluelanguage,tyingtogethersystemsandinterfacesthatwerenotspecificallydesignedtointeroperateSystemsadministratorsusePerlasanallpurposetool;shortPerlprogramscanbeenteredandrunonasinglecommandline
PhilosophyPerlhasseveralmottosthatconveyaspectsofitsdesignanduseOneisThere'smorethanonewaytodoit(TMTOWTDIusuallypronounced'TimToady')AnotherisPerl:theSwissArmyChainsawofProgrammingLanguagesAstateddesigngoalofPerlisto"makeeasytaskseasyanddifficulttaskspossible"
Perlisfreesoftware,andmaybedistributedundereithertheArtisticortheGPLLicenseItisavailableformostoperatingsystemsbutisparticularlyprevalentonUnixandUnixlikesystems(suchasLinux,FreeBSD,andMacOSX),andisgrowinginpopularityonMicrosoftWindowssystems
Perl/TkRequirementsBeforestartingwiththetutorial,makesureyouhavethefollowingthingsIfsomearemissingyoustillcanlearnperlbutyouwillnotbeabletouseittoitsfullpower
1. ActivePerl fromhttp://wwwactivestatecom/ActivePerl/forwindowsforprogramminginWindowsLinuxdon'tneedanyspecialoutsideinterpreterbecauseitalreadyhasitinmostofthedistributions
2. AgoodtexteditorIwouldrecommendCrimsonEditor(http://wwwcrimsoneditorcom/)forWindowsandXEmacsforLinux
Installing/UsingPerlInUnix/Linuxyoucanexecuteyourperlscriptsbytyping"perl"atcommandpromptButbeforeyoudothatmakesureyouhavebothPerlanditsTkmoduleMostlinuxdistributionshaveperlbutquiteafewdon'thavetheTkmoduleMakesurethatthesystemyouareusinghavetheTkmoduleIfyoudon'thaveit,gotohttp://wwwcpanorganddownloadtheperlmoduleOryoucanusetheperl'sCPANmoduletoinstalltheTkmoduleTodothis,openaterminalandenterthefollowingcommandperl -MCPAN -e shellcpan> install Bundle::CPANcpan> reload cpancpan> install TkAnother(andamucheasier)waytodothisistogetarpmofPerl/Tkandinstallingitwiththecommandrpm -ivh FILENAMEIfyouareusingUbuntu,aeasywayofinstallingPerl/Tkisusingthiscommand
sudo apt-get install perl-tkIfyouareusingWindows,downloadActivePerlandinstallitThenyoucanexecuteanyperlfilebydoubleclickingit
TwomorethingsbeforewebeginthetutorialIwillbeteachingperl/tkandIexpectyoutoknowhowtoprograminperlImayignoresomeoftheperlcodingconventionslikeincludinguse strict;,-woruse warnings;inmyexamplesTheexampleshaveonlyonepurposetodemonstratethefeaturethatwillbetaughtinthatpartofthetutorialSorryaboutthatbutIhavetokeepmytutorial'sexamplescriptsshortandtothepoint
Finally,thisisatutorialforPerl/TkonlyIwillnotbeteachingperlhereSoifyouknowperl,continueButifyouareabeginnertoperl,Iwouldrecommendthatyoureadmyperltutorial
HelloWorldLetusbegin,asallothertutorialsbegin,withthe"HelloWorld"programCreateafilecalled"Hellopl"andenterthefollowingintoit
#!/usr/local/bin/perluse Tk;# Main Windowmy $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,ittellsthenameofthescriptlanguageprocessorInourcaseitisperlDon'tunderstandwhatthatmeans?Don'tworryyourgraycellsoveritJustputitatthetopofthefile
Thesecondlineuse Tk;tellstheinterpreterthatourprogramwillusetheTkmoduleThislineisanabsolutemust
inallGUIprogramsyoumakeusingperlWhentheinterpreterencountersthisline,itwillloadtheTkcomponentsthatwewillbeusingtocreateourprogram
ThethirdlineThisisacommentAnylinethatstartswitha'#'charisacommentCommentsarenotofanyuseintheprogramItisusedbyprogrammertotalktothemselvesAprogrammercannotbeexpectedtoremembereverythingascriptdoesSoheusesacommenttowriteitdownNexttimeheeditsthescript,hecanreadthecommentandunderstandwhattheprogramisforItisgoodpracticetomakeasmuchcommentsaspossible
Thefourthline,my $mw = new MainWindow;,willcreateawindowintowhichtheGUIelementswillbeplacedThevariable$mwisaobjectoftype'MainWindow'Wewillhavetousethiselementwhenwewanttoplaceanywidgetinsideit
Thefifthline$mw -> Label(-text=>"Hello World") -> pack();makesalabelandwrites"Helloworld"initYoucanchangethetexttoanythingyoulikeNotethestructureofthecommand
$labelThisvariableassignedtothatparticularwidgetEverwidgetmusthaveaUNIQUEvariableThisnamewillbeusedwheneverthatwidgetmustbeaccessed
$mw -> $mwistheMainWindow'sobjectWewillbeplacingourlabelwidgetinsidethiswindowLabel(-text=>"Hello World")'Label'isthenameofthewidgetAwidgetisauserinterfaceobjectinXgraphicaluserinterfacesConfused?LetsjustsaythatitisthenameoftheobjectthatappearsonscreenTherearemanyotherwidgetstooIfyouwanttodisplayabutton,youusethebuttonwidgetFortext,youusethetextwidgetForentry,youguessedit,theentrywidgetIfyouwant,youcanseemoreaboutwidgets
text=>"HelloWorld"TheoptionforthiswidgetThisoptionsaysthatthiswidgetmustbegiventhetext"HelloWorld"OptionschangeaccordingtothewidgetsabuttonwidgetwillnothavealltheoptionsofthelabelwidgetandviseversaButtherewillbemanycommononesPleasenotethatoperatorusedhereis'=>'asopposedtotheoneusedearlier'>'in$mw ->Oneusestheminus()signwhiletheotherusestheequals(=)signDonotconfusebetweenthesetwoYoucankeepwritingotheroptionscanalsobewrittenhereForexample,letusmakealabelforshowingthetext"HelloWorld"TheotherlinesaresameastheHelloWorldprogram
$mw -> Label(-text=>"Hello World",-font=>"courierfont",-relief=>"raised") -> pack();Inthisexample,alotmoreoptionsareusedThefontoptionisusedtotellwhichfontmustbeusedtomakethetextandthereliefoptiontellswhetherthetextshouldappearraised,sunken,flatetcToknowalltheoptionsforaparticularwidget,readthemanualthatcomeswithPerlItlistseverywidgetandeveryoptiontheyhaveIfyouaregoingtoprograminPerl,youwillfindyourselfpeekingintothemanualeveryfewminutesThemostimportantandmostcommonlyusedoptionsarelistedhere
AlloptionsmustseparatedbyacommaButasyouhavenoted,thislineisalittledifficulttoreadAsthenumberofoptionsincrease,themoredifficulttoreaditSoamorereadableversionis
$mw -> Label(-text=>"Hello World", -font=>"courierfont", -relief=>"raised") -> pack();
Nextcomesthe-> pack();Thiswillpackthewidget'$label'intothewindow'$mw''pack'isageometrymanagerAnothergeometrymanageris'grid'Personally,IlikegridbetterOnceagain,puttingallthisinonelineisaneyesoresoyoucanputthispartinthenextline
my $label = $mw -> Label(-text=>"Hello World") -> pack();
Inthiscase,packhasnooptionswithinitButthatisnotalwaysthecase
my $label = $mw -> Label(-text=>"Hello World") -> pack(-side=>"left", -anchor=>'w');
Youdon'thavetopackthewidgetinthesamelineofcreatingitbutitisconvenientinsmallprogramsYoucanpackthewidgetlaterusingthewidget'svariableForexample
my $label = $mw -> Label(-text=>"Hello World"); #We created the widget$label -> pack(-side=>"left", -anchor=>'w'); #We pack it in another line
Sowehavethefinalsyntaxofhowtocreateanddisplayawidgetmy $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,wewillfindtwooptions'text'and'command'ThegiventextisQuitsothebuttonwillhavethetext"Quit"onitThecommandoptiondetermineswhatshouldhappenwhentheuserclickonthebuttonYoucanspecifyafunctiontoexecutewhentheuserclicksonthebuttonInthiscasetheprogramwillexitwhenthisbuttonispressedOnecanalsocallfunctionsthatyouhavecreatedfromhere
#!/usr/local/bin/perl
use Tk;# Main Windowmy $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;istheMainLooportheEventLoopItsjobistoinvokecallbacksinresponsetoeventssuchasbuttonpressesortimerexpirationsIfthislineismissing,theprogramwillrunandexitwithoutwaitingfortheusertodoanythingThisisanotheroneofthose'absolutemusts'ofPerl/Tkprogramming
NowPerlpuritanswillraiseagreathueandcryandsaythatthisisnotthewaytoprint"HelloWorld"The"pure"methodisthefollowing
#!/usr/local/bin/perlprint "Hello World"Puttingthingsinperspective,IamteachingPerl/TknotPerlTheaboveisthePerlmethodofdoingitMymethodisthepTkmethodofdoingit
Widgets1:Button,Entry,LabelAwidgetisauserinterfaceobjectinXgraphicaluserinterfacesConfused?LetsjustsaythatitisthenameoftheobjectthatappearsonscreenTherearemanytypeswidgetsIfyouwanttodisplayabutton,youusethebuttonwidgetFortext,youusethetextwidgetForentry,youguessedit,theentrywidgetSyntax:my$WidgetVariable=$Window>WidgetType(?Option1=>Value1,?Option2=>Value2??)>pack();
ThreethingsneedtobesaidaboutwidgetsFirstisthewidgetvariableThisIhaveexplainedearlierThewidgetvariableofallwidgetsmustbeuniqueandwillbeusedwheneverthatwidgetneedstobeaccessedSecondistheoptionsEachwidgethassomeoptionswhichcanbeusedtoconfigureitThisisusuallydonewhenthewidgetisdeclared,butitcanbedoneafterwardalsoThefinalthingiscommandsEachwidgethassomecommandswhichalso
canbeusedtoconfigureitormakeitdosomething
Butbeforewebegin,weneedtoknowalittleaboutthepackcommandIhaveexplainedthisearlierbutjustdoingitonemoretimesothatyoudon'thavetopushthebackbuttonPackisageometrymanagerAnothergeometrymanageris'grid'wewillexplorethatlatterPackismuchmoresimplerthangridTheline$hello>pack;tellstheinterpretertopackthewidgetcalled"$hello"
ButtonThiswillmakeabuttonItcanbeconfiguredtoexecutesomecodewhenthebuttonispushedThiswillusuallyrefertoafunctionsowhenthebuttonispushed,thefunctionwillrunAnbuttonisshownbelowThisbuttoniscreatedusingHTMLinputtag
SomeOptionstext=>"TEXT" TEXTwillbethetextdisplayedonthebutton
command=>CALLBACK CALLBACKwillbethecodethatiscalledwhenthebuttonispushed
#!/usr/local/bin/perluse Tk;
# Main Windowmy $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);)Makesurethattheslashstaystheretoseewhy,gototheMostcommonmistakesbyPerl/Tkbeginners
EntryAnentryisawidgetthatdisplaysaonelinetextstringandallowstheusertoinputandedittextinitWhenanentryhastheinputfocusitdisplaysaninsertioncursortoindicatewherenewcharacterswillbeinsertedAnentryelementisshownusingHTML
SomeOptionswidth=>NUMBER WidthoftheinputfieldNUMBERshouldbeaninteger
textvariable=>\$VARIABLE ThecontentsofthevariableVARIABLEwillbedisplayedinthewidgetIfthetextinthewidgetisedited,thevariablewillbeeditedautomatically
state=>STATEThestateoftheinputfieldItcanbenormal,disabled,orreadonlyIfitisreadonlythetextcan'tbeedited
SomeCommands
Syntax Description Example
$widget>get(); Thetextinsideinputfieldcanbetakenbythiscommand
$name=$ent>get();
$widget>delete(FIRST?,LAST?); DeleteoneormoreelementsoftheentryFIRSTis $ent>delete(0,'end');
theindexofthefirstcharactertodelete,andLASTistheindexofthecharacterjustafterthelastonetodeleteIflastisn'tspecifieditdefaultstoFIRST+1,ieasinglecharacterisdeletedThiscommandreturnsanemptystring
$widget>insert(index,"STRING");
InsertthecharactersofSTRINGjustbeforethecharacterindicatedbyindexIndexis0forthefirstcharacterTheword"end"canbeusedforthelastcharacter
$ent>insert('end',"Hello");
Example
#!/usr/local/bin/perluse Tk;
# Main Windowmy $mw = new MainWindow;
#GUI Building Areamy $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");}
LabelThiswidgetdisplaytextmessages
SomeOptionstext=>"TEXT" TEXTwillbethetextdisplayedonthebutton
font=>FONT SpecifiesthefonttousewhendrawingtextinsidethewidgetYoucanspecifyjustthefontoryoucangiveitinthisformat"FONTNAMESIZESTYLE"TheSTYLEcanbebold,normaletc
Example
#!/usr/local/bin/perluse 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 pressedsub push_button { $ent -> insert(0,"Hello, ");}
Widgets2:Frame,Text,Scrollbar,Scale
FrameAframeisasimplewidgetItsprimarypurposeistoactasaspacerorcontainerforcomplexwindowlayoutsTheonlyfeaturesofaframeareitsbackgroundcolorandanoptional3DbordertomaketheframeappearraisedorsunkenFramecanbecreatedjustlikeanyotherwidgetmy $frm = $mw -> Frame();Toplaceotherwidgetsinthisframe,youshouldusetheframewidgetvariableasitsparentNormallytheparentis'$mw'ortheMainWindowButifwewishtoputawidgetinsideaframe,usetheframevariable('$frm'inthiscase)inplaceof'$mw'Likethismy $lab = $frm_name -> Label(-text=>"Name:") -> pack();SomeOptions
relief=>STYLE
Specifiesthe3DeffectdesiredforthewidgetAcceptablevaluesareraised,sunken,flat,ridge,solid,andgrooveThevalueindicateshowtheinteriorofthewidgetshouldappearrelativetoitsexterior;forexample,raisedmeanstheinteriorofthewidgetshouldappeartoprotrudefromthescreen,relativetotheexteriorofthewidget
Example
#!/usr/local/bin/perluse Tk;
my $mw = new MainWindow; # Main Window
my $frm_name = $mw -> Frame() -> pack(); #New Framemy $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 pushedsub push_button { $ent -> insert(0,"Hello, ");}
TextAtextwidgetdisplaysoneormorelinesoftextandallowsthattexttobeeditedSimilartotheentrywidgetbutalargerversionofit
SomeOptions
xscrollcommand=>COMMAND ThisistoenablecommunicationbetweenatextwidgetandascrollbarwidgetThereisayscrollcommandsimillertothisone
font=>FONTNAME Specifiesthefonttousewhendrawingtextinsidethewidget
width=>NUMBER Specifiesthewidthofthewidget
height=>NUMBER Specifiesthe,youguessedit,heightofthewidget
Syntax Description Example
$widget>get(index1,?index2?);
ReturnarangeofcharactersfromthetextThereturnvaluewillbeallthecharactersinthetextstartingwiththeonewhoseindexisindex1andendingjustbeforetheonewhoseindexisindex2(thecharacteratindex2willnotbereturned)Ifindex2isomittedthenthesinglecharacteratindex1isreturnedNotethattheindexoftextisdifferentfromthatoftheentrywidgetTheindexoftextwidgetisintheformLINE_NOCHARECTER_NOThismeansthat10meansthefirstcharacterinthefirstline
$contents=$txt>get(10,'end');
$widget>insert(index,DATA);
InsertsallofthecharsargumentsjustbeforethecharacteratindexIfindexreferstotheendofthetext(thecharacterafterthelastnewline)thenthenewtextisinsertedjustbeforethelastnewlineinstead
$txt>inset('end',"HelloWorld");
Example
#!/usr/local/bin/perluse 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 Areamy $txt = $mw -> Text(-width=>40, -height=>10) -> pack();
MainLoop;
#This function will be executed when the button is pushedsub push_button { my $name = $ent -> get(); $txt -> insert('end',"Hello, $name");}
ScrollbarAscrollbarisawidgetthatdisplaystwoarrows,oneateachendofthescrollbar,andasliderinthemiddleportionofthescrollbarItprovidesinformationaboutwhatisvisibleinanassociatedwindowthatdisplaysandocumentofsomesort(suchasafilebeingeditedoradrawing)ThepositionandsizeofthesliderindicatewhichportionofthedocumentisvisibleintheassociatedwindowForexample,ifthesliderinaverticalscrollbarcoversthetopthirdoftheareabetweenthetwoarrows,itmeansthattheassociatedwindowdisplaysthetopthirdofitsdocumentItismadetoworkwithotherwidgetsliketextSomeOptions
orient=>DIRECTIONForwidgetsthatcanlaythemselvesoutwitheitherahorizontalorverticalorientation,suchasscrollbars,thisoptionspecifieswhichorientationshouldbeusedDIRECTIONmustbeeitherhorizontalorverticaloranabbreviationofoneofthese
command=>COMMAND ThiscommandgetsexecutedwhenthescrollbarismovedThisoptionalmostalwayshas
avaluesuchastxviewortyview,consistingofthenameofawidgetandeitherxview(ifthescrollbarisforhorizontalscrolling)oryview(forverticalscrolling)Allscrollablewidgetshavexviewandyviewcommandsthattakeexactlytheadditionalargumentsappendedbythescrollbar
Example
#!/usr/local/bin/perluse 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 Framemy $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 pushedsub push_button { my $name = $ent -> get(); $txt -> insert('end',"Hello, $name");}
grid
AsyoucanseeIhaveused'grid'hereGridisNOTawidgetItisageometrymanagerlikepackbutmoreadvancedLetstakeacloserlookatthecommands$widget -> grid(-row=>1, -column=>1);Thislinewilltelltheinterpretertoputthewidgetcalled'$txt'inthefirstrowofthefirstcolumnofitsparentwidgetThebelowdigramwillhelpyouunderstand
Column1 Column2
Row1 '$txt'widgetwillbehere '$srl_y'widget'splace
Row2 '$srl_x'widget'sposition
SomeOptions
sticky=>STYLE
Thisoptionmaybeusedtoposition(orstretch)thewidgetwithinitscellSTYLEisastringthatcontainszeroormoreofthecharactersn,s,eorwEachletterreferstoaside(north,south,east,orwest)thattheslavewill"stick"toIfbothnands(oreandw)arespecified,theslavewillbestretchedtofilltheentireheight(orwidth)ofitscavity
ipadx=>AMOUNT TheAMOUNTspecifieshowmuchhorizontalinternalpaddingtoleaveoneachsideoftheslave(s)Thisisspaceisaddedinsidetheslave(s)border
ipady=>AMOUNT TheAMOUNTspecifieshowmuchverticalinternalpaddingtoleaveoneachsideoftheslave(s)Optionssameasipadx
padx=>AMOUNTTheamountspecifieshowmuchhorizontalexternalpaddingtoleaveoneachsideoftheslave(s),inscreenunitsAMOUNTmaybealistoftwovaluestospecifypaddingforleftandrightseparately
pady=>AMOUNT Theamountspecifieshowmuchverticalexternalpaddingtoleaveonthetopandbottomoftheslave(s),inscreenunitsOptionssameaspadx
row=>NInserttheslavesothatitoccupiestheNthrowinthegridRownumbersstartwith0Ifthisoptionisnotsupplied,thentheslaveisarrangedonthesamerowasthepreviousslavespecifiedonthiscalltogrid,orthefirstunoccupiedrowifthisisthefirstslave
column=>N InserttheslavesothatitoccupiestheN'thcolumninthegridOptionssameasrow
rowspan=>N InserttheslavesothatitoccupiesNrowsinthegridThedefaultisonerow
columnspan=>N InserttheslavesothatitoccupiesNcolumnsinthegrid
UsinggridrequiresabitofexperiencebutifyouknowHTMLitwouldhelpalotTherowsandcolumnsarejustlikethoseinHTMLtablesalthoughthecodesareverydifferent
Scale
Makesasliderthatcanbeadjustedbytheusertoinputavariable
SomeOptionsfrom=>NUMBER StartingNumber
to=>NUMBER EndingNumber
tickinterval=>NUMBER Determinesthespacingbetweennumericaltickmarksdisplayedbelowortotheleftoftheslider
varable=>NAMESpecifiesthenameofaglobalvariabletolinktothescaleWheneverthevalueofthevariablechanges,thescalewillupdatetoreflectthisvalueWheneverthescaleismanipulatedinteractively,thevariablewillbemodifiedtoreflectthescale'snewvalue
Syntax Description Example
$widget>get(); Getthecurrentvalueofthescale my$age=$scl>get();
$widget>set(value); Givethescaleanewvalue $scl>set(20);
Example
#!/usr/local/bin/perluse Tk;
#Global Variablesmy $age = 10;
# Main Windowmy $mw = new MainWindow;
#GUI Building Areamy $frm_name = $mw -> Frame();my $lab = $frm_name -> Label(-text=>"Name:");my $ent = $frm_name -> Entry();#Agemy $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 Areamy $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 pushedsub push_button { my $name = $ent -> get(); $txt -> insert('end',"$name is $age years old");}
NowourlittleexampleisbecomingmoreandmorelikeaprogramWehaveaddedthecommentstoitasithasgrownbigandisdifficulttounderstandNowwehaveaddedasliderwithwhichagecanbeinputed
DialogsDialogscanbecalledtheelementsinaprogramthatdetachesitselffromthemainwindowThisisaVERYgeneraldefinitionandhasmanyproblemsButforthemoment,itwilldoTkprovidesmanydialogs
messageBoxThisprocedurecreatesanddisplaysamessagewindowwithanapplicationspecifiedmessage,aniconandasetofbuttonsEachofthebuttonsinthemessagewindowisidentifiedbyauniquesymbolicname(seethetypeoptions)Afterthemessagewindowispoppedup,messageBoxwaitsfortheusertoselectoneofthebuttonsPushthebelowbuttontoseeanexampleofmessageBox
SomeOptionsdefault=>name Namegivesthesymbolicnameofthedefaultbuttonforthismessagewindow('ok','cancel',
andsoon)SeetypeforalistofthesymbolicnamesIfthisoptionisnotspecified,thefirst
buttoninthedialogwillbemadethedefault
icon>iconImage SpecifiesanicontodisplayIconImagemustbeoneofthefollowing:error,info,questionorwarningIfthisoptionisnotspecified,thentheinfoiconwillbedisplayed
message>string Specifiesthemessagetodisplayinthismessagebox
title>String SpecifiesastringtodisplayasthetitleofthemessageboxThedefaultvalueisanemptystring
type>predefinedType
ArrangesforapredefinedsetofbuttonstobedisplayedThefollowingvaluesarepossibleforpredefinedType:abortretryignore Displaysthreebuttonswhosesymbolicnamesareabort,retryandignoreok Displaysonebuttonwhosesymbolicnameisokokcancel Displaystwobuttonswhosesymbolicnamesareokandcancelretrycancel Displaystwobuttonswhosesymbolicnamesareretryandcancelyesno Displaystwobuttonswhosesymbolicnamesareyesandnoyesnocancel Displaysthreebuttonswhosesymbolicnamesareyes,noandcancel
Example
#!/usr/local/bin/perluse Tk;use strict;
# Main Windowmy $mw = new MainWindow;my $button = $mw-
providingaseparateNewmenucommand
ThegetSaveFilecommandisusuallyassociatedwiththeSaveascommandintheFilemenuIftheuserentersafilethatalreadyexists,thedialogboxpromptstheuserforconfirmationwhethertheexistingfileshouldbeoverwrittenornot
SomeOptions
initialdir=>DIRNAME
SpecifiesthatthedirectoriesindirectoryshouldbedisplayedwhenthedialogpopsupIfthisparameterisnotspecified,thenthedirectoriesinthecurrentworkingdirectoryaredisplayedIftheparameterspecifiesarelativepath,thereturnvaluewillconverttherelativepathtoanabsolutepath
defaultextension=>EXTENSIONSpecifiesastringthatwillbeappendedtothefilenameiftheuserentersafilenamewithoutanextensionThedefaultvalueistheemptystring,whichmeansnoextensionwillbeappendedtothefilenameinanycase
filetypes=>filePatternList
IfaFiletypeslistboxexistsinthefiledialogontheparticularplatform,thisoptiongivesthefiletypesinthislistboxWhentheuserchooseafiletypeinthelistbox,onlythefilesofthattypearelistedIfthisoptionisunspecified,orifitissettotheemptylist,oriftheFiletypeslistboxisnotsupportedbytheparticularplatformthenallfilesarelistedregardlessoftheirtypesThisisalittletrickyseemanualforinformation
initialfile=>FILENAME Specifiesafilenametobedisplayedinthedialogwhenitpopsup
multiple AllowstheusertochoosemultiplefilesfromtheOpendialog
TopleveltoplevelisawidgetThiscanbeusedtocreatecustomdialogboxesAtoplevelissimilartoaframeexceptthatitiscreatedasatoplevelwindow:itsXparentistherootwindowofascreenratherthanthelogicalparentfromitspathnameTheprimarypurposeofatoplevelistoserveasacontainerfordialogboxesandothercollectionsofwidgetsTheonlyvisiblefeaturesofatoplevelareitsbackgroundcolorandanoptional3Dbordertomakethetoplevelappearraisedorsunken
OnecanusetopleveltocreatenewwindowsThewidgetscanbepackedinsideitinthesamewaywidgetsarepackedinsideaframeAnexample
#!/usr/local/bin/perluse 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 windowsub 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
RadiobuttonisaninputwhereanyoneofmanychoicesMUSTbechosenIfoneischosenandanotherbuttonisclicked,thelastchosenwillloseitsstateandtheclickedbuttonwillbechosenAgraphicexample(inHTML)isgivenbelow
Choices 1| 2| 3
SomeOptions
command=>COMMAND SpecifiesacommandtoassociatewiththebuttonThiscommandistypicallyinvokedwhenmousebutton1isreleasedoverthebuttonwindow
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/perluse Tk;
#Global Variablesmy $age = 10;my $gender = "Male";
# Main Windowmy $mw = new MainWindow;
#GUI Building Areamy $frm_name = $mw -> Frame();my $lab = $frm_name -> Label(-text=>"Name:");my $ent = $frm_name -> Entry();#Agemy $scl = $mw -> Scale(-label=>"Age :", -orient=>'v', -digit=>1, -from=>10, -to=>50, -variable=>\$age, -tickinterval=>10);
#Gendermy $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 Areamy $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 pushedsub push_button { my $name = $ent -> get(); $txt -> insert('end',"$name\($gender\) is $age years old");}
ThistimetheprogramissubjectedtoevenmorechangethegeometrymanagerisfullygridnowThereisnoinstancesofpackYouwillfindthisnecessarywhenthelayoutbecomesmorecomplicatedIhopeyoucanstaywithmeinsuchtryingtimes
Checkbutton
CheckbottonisainputwithtwooptionsOfforOnithastobeeitheroneThestatecanbechangedbyclickingonitAnexampleisshownbelow
checkbox
SomeOptions
offvalue=>VALUE Specifiesvaluetostoreinthebutton'sassociatedvariablewheneverthisbuttonisdeselectedDefaultsto``0''
onvalue=>VALUE Specifiesvaluetostoreinthebutton'sassociatedvariablewheneverthisbuttonisselectedDefaultsto``1''
command=>CALLBACK SpecifiesacommandtoassociatewiththebuttonThiscommandistypicallyinvokedwhenmousebutton1isreleasedoverthebuttonwindow
variable=>\$VARABLE Specifiesnameofglobalvariabletosettoindicatewhetherornotthisbuttonisselected
Syntax Description Example
$widget>deselect(); Deselectsthecheckbuttonandsetstheassociatedvariabletoits``off''value $chk>deselect();
$widget>select(); Selectsthecheckbuttonandsetstheassociatedvariabletoits``on''value $chk>select();
$widget>toggle(); Togglestheselectionstateofthebutton,redisplayingitandmodifyingitsassociatedvariabletoreflectthenewstate $chk>toggle();
Example
#!/usr/local/bin/perluse Tk;
#Global Variablesmy $age = 10;my $gender = "Male";my $occupied = 1;
# Main Windowmy $mw = new MainWindow;
#GUI Building Areamy $frm_name = $mw -> Frame();my $lab = $frm_name -> Label(-text=>"Name:");my $ent = $frm_name -> Entry();#Agemy $scl = $mw -> Scale(-label=>"Age :", -orient=>'v', -digit=>1, -from=>10, -to=>50, -variable=>\$age, -tickinterval=>10); #Jobsmy $chk = $mw -> Checkbutton(-text=>"Occupied", -variable=>\$occupied);$chk -> deselect();
#Gendermy $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 Areamy $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");
$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 pushedsub push_button { my $name = $ent -> get(); $txt -> insert('end',"$name\($gender\) is $age years old");}
Widgets4:Listbox
ListboxAlistboxisawidgetthatdisplaysalistofstrings,oneperlineWhenfirstcreated,anewlistboxhasnoelementsElementsmaybeaddedordeletedusingwidgetcommandsdescribedbelow
SomeOptions
selectmode=>MODESpecifiesoneofseveralstylesformanipulatingtheselectionTheMODEmaybearbitrary,butthedefaultbindingsexpectittobeeithersingle,browse,multiple,orextended;thedefaultvalueisbrowse
SomeCommands
Syntax Description Example
$widget>curselection();
ReturnsalistcontainingthenumericalindicesofalloftheelementsinthelistboxthatarecurrentlyselectedIftherearenoelementsselectedinthelistboxthenanemptystringisreturned
$sel=$lst>curselection();
$widget>delete(first,?last?);
DeletesoneormoreelementsofthelistboxFirstandlastareindicesspecifyingthefirstandlastelementsintherangetodeleteIflastisn'tspecifieditdefaultstofirst,ieasingleelementisdeleted
$lst>delete(5);
$widget>get(first,?last?);
Iflastisomitted,returnsthecontentsofthelistboxelementindicatedbyfirst,oranemptystringiffirstreferstoanonexistentelementIflastisspecified,thecommandreturnsalistwhoseelementsareallofthelistboxelementsbetweenfirstandlast,inclusive
$lst>get(5,end);
$widget>index(index);
ReturnstheintegerindexvaluethatcorrespondstoindexIfindexisendthereturnvalueisacountofthenumberofelementsinthelistbox(nottheindexofthelastelement)
$lst>index(5);
$widget>insert(index,?elementelement?);
InsertszeroormorenewelementsinthelistjustbeforetheelementgivenbyindexIfindexisspecifiedasendthenthenewelementsareaddedtotheendofthelistReturnsanemptystring
$lst>insert('end',"me");
$widget>size(); Returnsadecimalstringindicatingthetotalnumberofelementsinthelistbox
$count=$lst>size();
Example
#!/usr/local/bin/perluse Tk;
#Global Variablesmy $age = 10;my $occupied = 1;my $gender = "Male";
# Main Windowmy $mw = new MainWindow;
#GUI Building Areamy $frm_name = $mw -> Frame();my $lab = $frm_name -> Label(-text=>"Name:");my $ent = $frm_name -> Entry();#Agemy $scl = $mw -> Scale(-label=>"Age :", -orient=>'v', -digit=>1, -from=>10, -to=>50, -variable=>\$age, -tickinterval=>10);
#Jobsmy $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");
#Gendermy $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 Areamy $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 pushedsub 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'fromnowonThisisquitecomplicatedisn'tit?Whydon'tyourunthescriptandseewhatabeautifulscriptwemadeCopytheabovescriptandpasteitinafilecalled"infopl"anddoubleclickthefileVoila!WearePerl/Tkprogrammers
Widgets5:Menubutton,Menu,Optionmenu
MenubuttonAmenubuttonisawidgetthatdisplaysatextualstring,bitmap,orimageandisassociatedwithamenuwidgetInnormalusage,pressingleftclickingthemenubuttoncausestheassociatedmenutobepostedjustunderneaththemenubutton
SomeOptions
direction=>DIRECTION
Specifieswherethemenuisgoingtobepopupupabovetriestopopthemenuabovethemenubuttonbelowtriestopopthemenubelowthemenubuttonlefttriestopopthemenutotheleftofthemenubuttonrighttriestopopthemenutotherightofthemenubuttonflushpopsthemenudirectlyoverthemenubutton
menu=>NAME SpecifiesthepathnameofthemenuassociatedwiththismenubuttonThemenumustbeachildofthemenubutton
MenuAmenuisawidgetthatdisplaysacollectionofonelineentriesarrangedinoneormorecolumnsThereexistseveraldifferenttypesofentries,eachwithdifferentpropertiesEntriesofdifferenttypesmaybecombinedinasinglemenuMenuentriesarenotthesameasentrywidgetsInfact,menuentriesarenotevendistinctwidgets;theentiremenuisonewidget
SomeOptions
tearoff=>BOOLEAN
Thisoptionmusthaveaproperbooleanvalue,whichspecifieswhetherornotthemenushouldincludeatearoffentryatthetopIfso,itwillexistasentry0ofthemenuandtheotherentrieswillnumberstartingat1Thedefaultmenubindingsarrangeforthemenutobetornoffwhenthetearoffentryisinvoked
title=>STRINGThestringwillbeusedtotitlethewindowcreatedwhenthismenuistornoffIfthetitleisNULL,thenthewindowwillhavethetitleofthemenubuttonorthetextofthecascadeitemfromwhichthismenuwasinvoked
type=>OPTIONThisoptioncanbeoneofmenubar,tearoff,ornormal,andissetwhenthemenuiscreatedWhilethestringreturnedbytheconfigurationdatabasewillchangeifthisoptionischanged,thisdoesnotaffectthemenuwidget'sbehavior
SomeCommands
Syntax Description
$widget>TYPE(?option=>value,option=>value,?);
AddanewentrytothebottomofthemenuThenewentry'stypeisgivenbyTYPEandmustbeoneofcascade,checkbutton,command,radiobutton,orseparator,orauniqueabbreviationofoneoftheaboveIfadditionalargumentsarepresent,theyspecifyanyofthefollowingoptions:
accelerator=>VALUE
SpecifiesastringtodisplayattherightsideofthemenuentryNormallydescribesanacceleratorkeystrokesequencethatmaybetypedtoinvokethesamefunctionasthemenuentryThisoptionisnotavailableforseparatorortearoffentries
columnbreak=>VALUEWhenthisoptioniszero,theappearsbelowthepreviousentryWhenthisoptionisone,themenuappearsatthetopofanewcolumninthemenu
label=>VALUE SpecifiesastringtodisplayasanidentifyinglabelinthemenuentryNotavailableforseparatorortearoffentries
compound=>VALUE
Specifieswhetherthemenuentryshoulddisplaybothanimageandtext,andifso,wheretheimageshouldbeplacedrelativetothetextValidvaluesforthisoptionarebottom,center,left,none,rightandtop
image=>VALUE
SpecifiesanimagetodisplayinthemenuinsteadofatextstringorbitmapTheimagemusthavebeencreatedbysomepreviousinvocationofimagecreateThisoptionoverridesthelabelandbitmapoptionsbutmayberesettoanemptystringtoenableatextualorbitmaplabeltobedisplayedThisoptionisnotavailableforseparatorortearoffentries
underline=>VALUE
SpecifiestheintegerindexofacharactertounderlineintheentryThisoptionisusedtomakekeyboardshortcuts0correspondstothefirstcharacterofthetextdisplayedintheentry,1tothenextcharacter,andsoon
$widget>delete(index1,?index2?);
Deleteallofthemenuentriesbetweenindex1andindex2inclusiveIfindex2isomittedthenitdefaultstoindex1Attemptstodeleteatearoffmenuentryareignored(instead,youshouldchangethetearOffoptiontoremovethetearoffentry)
$widget>insert(index,type,?option=>value?);
Sameastheaddwidgetcommandexceptthatitinsertsthenewentryjustbeforetheentrygivenbyindex,insteadofappendingtotheendofthemenuThetype,option,andvalueargumentshavethesameinterpretationasfortheaddwidgetcommandItisnotpossibletoinsertnewmenuentriesbeforethetearoffentry,ifthemenuhasone
Example
#!/usr/local/bin/perluse Tk;# Main Windowmy $mw = new MainWindow;
#Making a text areamy $txt = $mw -> Scrolled('Text',-width => 50,-scrollbars=>'e') -> pack ();
#Declare that there is a menumy $mbar = $mw -> Menu();$mw -> configure(-menu => $mbar);
#The Main Buttonsmy $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 AWebsite : 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 tutorialMade by Binny V AWebsite : http://wwwgeocitiescom/binnyva/codeE-Mail : binnyva\@hotmailcom"); });
MainLoop;
sub menuClicked { my ($opt) = @_; $mw->messageBox(-message=>"You have clicked $optThis function is not implanted yet");}
CreatethemainbuttonsascascademenusandcreatethemenusastheirslavesFormoreinformationseethemanual
OptionmenuMakesabutton,whichwhenclickedonshowsalistwithavailableoptionsUsefulwhenuserhastomakeonechoicewhenmultiplechoicesaregivenBelowisaoptionsmenuinHTMLAwordofcautionthoughPerl/Tk'soptionmenuhasaverydifferentappearance
Syntaxmy $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]?);
Addsnewlygivenoptionstothealreadyavailableoptions
$opt>addOptions([May=>5],[June=>6],[July=>7],[Augest=>8]);
Example
#!/usr/local/bin/perluse 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
CanvasThecanvaswidgetisaveryimportantwidgetasallpointsareaddressablegraphicaldrawingareaCanvaswidgetsimplementstructuredgraphicsAcanvasdisplaysanynumberofitems,whichmaybethingslikerectangles,circles,lines,andtextItemsmaybemanipulated(egmovedorrecolored)andcommandsmaybeassociatedwithitemsSoifyoudon'tlikethepaintprograminwindows,youcanmakeyourownprogramusingthiswidget
Go
Thecommand$widget -> create typeoptionsisusedtomakedifferentstructuresAfewexamplesaregivenbelowFormoreinformationreadthemanual
Example
#!/usr/local/bin/perluse Tk;# Main Windowmy $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;
MessageAmessageisawidgetthatdisplaysatextualstringMuchlikethelabelwidgetbutthiscanbeusedtomakeamultilinetext
ThejustifyoptionspecifieshowtojustifylinesoftextMustbeoneofleft,center,orrightDefaultstoleftThisoptionworkstogetherwiththeanchor,aspect,padX,padY,andwidthoptionstoprovideavarietyofarrangementsofthetextwithinthewindow
Adjuster
AnadjusteractsliketheframewidgetwithonenotableexceptionTheborderscanbedraggedandexpendedThiswidgetcontainsanynumberofpanes,arrangedhorizontallyorvertically,accordingtothevalueoftheorientoptionEachpanecontainsonewidget,andeachpairofpanesisseparatedbyamovablesashMovingasashcanbedonebydraggingitThiscausesthewidgetsoneithersideofthesashtoberesized
SomeOptions
side=>DIRECTIONSpecifiesthesideonwhichthemanagedwidgetliesrelativetotheAdjusterInconjunctionwiththepackgeometrymanager,thisrelatestothesideofthemasteragainstwhichthemanagedwidgetandtheAdjusterarepackedMustbeleft,right,top,orbottomDefaultstotop
SomeMethods
$adjuster>packAfter($widget,?pack_options?)
ThiscommandconfigurestheAdjuster'swidgetandsideoptionsrespectivelyto'$widget'andthesidevaluespecifiedinpack_options(topifnotspecified)ItthenpackstheAdjusterafter'$widget',withfillsettoxoryasappropriate
Exampleuse Tk;use Tk::Adjuster;my $mw = new MainWindow;
my $adj = $mw -> Adjuster();my $lst = $mw -> Listbox();
$lst -> insert('end', "Item 1");$lst -> insert('end', "Item 2");$lst -> insert('end', "Item 3");$lst -> insert('end', "Item 4");$lst -> insert('end', "Item 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)Ifyouhavetriedtocreateawidgetandattachscrollbarstoit,youwilldoubtlesslyunderstandtheusefulnessofthisfeatureItgreatlyreducesthenumberofcodeforthesesituations
my $widget = $parent -> Scrolled('WIDGET' ?,-scrollbars=>WHERE? ?,?);WIDGETcanbeanywidgetthatsupportsscrollingForexample,Text,Listbox,etc
SomeOptions
scrollbars=>SIDEExpectsasargumentthepositionwherethescrollbarsshouldbecreated:w,eorn,soracombinationofthemIftheoneorbothpositionsareprefixedwithothescrollbarwillonlyshowupifthereisa'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;
Thesameexampleusinghandcodedscrollbarsuse 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
gridThegridcommandisusedtocommunicatewiththegridgeometrymanagerthatarrangeswidgetsinrowsandcolumnsinsideofanotherwindow,calledthegeometrymaster(ormasterwindow)Thegridcommandcanhaveanyofseveralforms,dependingontheoptionargumentInshort,gridisthenamegiventothethingythatwillplaceyourwidgetwhereyouwantittobeplaced
SomeOptions
sticky=>STYLE
Thisoptionmaybeusedtoposition(orstretch)thewidgetwithinitscellSTYLEisastringthatcontainszeroormoreofthecharactersn,s,eorwEachletterreferstoaside(north,south,east,orwest)thattheslavewill"stick"toIfbothnands(oreandw)arespecified,theslavewillbestretchedtofilltheentireheight(orwidth)ofitscavity
ipadx=>AMOUNT TheAMOUNTspecifieshowmuchhorizontalinternalpaddingtoleaveoneachsideoftheslave(s)Thisisspaceisaddedinsidetheslave(s)border
ipady=>AMOUNT TheAMOUNTspecifieshowmuchverticalinternalpaddingtoleaveoneachsideoftheslave(s)Optionssameasipadx
padx=>AMOUNTTheamountspecifieshowmuchhorizontalexternalpaddingtoleaveoneachsideoftheslave(s),inscreenunitsAMOUNTmaybealistoftwovaluestospecifypaddingforleftandrightseparately
pady=>AMOUNT Theamountspecifieshowmuchverticalexternalpaddingtoleaveonthetopandbottomoftheslave(s),inscreenunitsOptionssameaspadx
row=>NInserttheslavesothatitoccupiestheNthrowinthegridRownumbersstartwith0Ifthisoptionisnotsupplied,thentheslaveisarrangedonthesamerowasthepreviousslavespecifiedonthiscalltogrid,orthefirstunoccupiedrowifthisisthefirstslave
column=>N InserttheslavesothatitoccupiestheN'thcolumninthegridOptionssameasrow
rowspan=>N InserttheslavesothatitoccupiesNrowsinthegridThedefaultisonerow
columnspan=>N InserttheslavesothatitoccupiesNcolumnsinthegrid
Example
#!/usr/local/bin/perluse Tk;
# Main Windowmy $mw = new MainWindow;#Text Areamy $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'inthefirstrowofthefirstcolumnofitsparentwidgetThebelowdigramwillhelpyouunderstand
Column1 Column2
Row1 '$xt'widgetwillbehere '$srl_y'widget'splace
Row2 '$srl_x'widget'sposition
UsinggridrequiresabitofexperiencebutifyouknowHTMLitwouldhelpalotTherowsandcolumnsarejustlikethoseinHTMLtablesTheconceptisthesamebutthecodesareverydifferent
packPackisalsoageometrymanagerlikeGridbutmuchsimplerYoudon'thavetospecifytherowsandcolumnsasyoudidforgridThisisforyoulazybonesoutthereJustput$widget -> pack;andthewidgetwillbepackedButformorecomplexarrangementswithpackonemustuseframes
SomeOptions
expand=>BOOLEANSpecifieswhethertheslavesshouldbeexpandedtoconsumeextraspaceintheirmasterSoundsalotlikeslaveseatinguptheirmasters,don'tit?Itjustmeansthatwhentheapplicationisresizedthewidgetswillautomaticallyfillthespace
fill=>STYLE Thiswillstretchthewidgetinxdirection,ydirectionorbothdirections
side=>SIDESpecifieswhichsideofthemastertheslave(s)willbepackedagainstMustbeleft,right,top,orbottomDefaultstotop
Nowfortheexample
#!/usr/local/bin/perluse Tk;
# Main Windowmy $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 ShowA Window Was Something You Hated To CleanAnd Ram Was The Cousin Of A Goat
Meg Was The Name Of My GirlfriendAnd Gig Was Your Thumb UprightNow They All Mean Different ThingsAnd That Mega Bytes
An Application Was For EmploymentA Program Was A TV ShowA Cursor Used ProfanityA Keyboard Was A Piano Compress Was Something You Did To The GarbageNot Something You Did To A FileAnd If You Unzipped Anything In PublicYou'd Be In Jail For A While
Log On Was Adding Wood To The FireHard Drive Was A Long Trip On The RoadA Mouse Pad Was Where A Mouse LivedAnd A Backup Happened To Your Commode
Cut You Did With A Pocket KnifePaste You Did With GlueA Web Was A Spider's HomeAnd A Virus Was The Flu
I Guess I'll Stick To My Pad And PaperAnd The Memory In My HeadI Hear Nobody's Been Killed In A Computer CrashBut, When It Happens They Wish They Were Dead");
my $srl = $mw -> Scrollbar(-command=>[$txt,'yview']);$txt -> configure(-yscrollcommand=>[$srl,'set']);
#The packing commands$lab -> pack;$txt -> pack(-expand => 1, -fill => "both", -side => "left");$srl -> pack(-expand => 1, -fill => "y");
MainLoop;
SomeCommonWidgetOptionsThecapitalizedwordmustbereplacedwithanyoftheboldwordsCheckthemanualforalltheoptionsAlsomakesurethatthewidgetyouareusingsupporttheoptionyouareusing
anchor=>POSITION Positionwidgetrelativeto:nnenwssesweworcenter
background=>COLOR Backgroundcolor
borderwidth=>WIDTH WidthofborderChoosing'0'willhidetheborder
command=>SCRIPT ExecutesSCRIPTwheninvoked
cursor=>CURSOR Mousecursortodisplaywhenmouseinthiswidget
disabledforeground=>COLOR
Foregroundcolorwhenthewidgetisdisabled
font=>FONTNAMEUseFONTNAMEfortextstyleItisgiveninthisformatFONTNAMESIZESTYLEForexample,-font => "fixed 12 bold"
foreground=>COLOR Foregroundwhenthestateofthewidgetisnormal
Cansetshorizontal(andoptionallyvertical)widgetsize
geometry=>WIDTHxHEIGHT
height=>VALUE Setverticalheightofthewidget
image=>IMAGE Theimagetodisplayinwidget
justify=>JUSTIFICATION
Multilinejustification:left,rightorcenter
orient=>ORIENTATION
ForobjectslikescaleandscrollbarMustbehorizontalorvertical(orhorv)
padx=>NUMBER HorizontalpaddingThespaceontopandbottomofthegivenwidgetForexample,padx=>5
pady=>NUMBER VerticalpaddingThisisthespaceoneithersideofthegivenwidgetForexample,pady=>2
relief=>RELIEF3DbevelborderRELIEFmustbeflat,groove,raised,ridge,solidorsunkenVeryusefulwhenusingframe
state=>STATE Setwidgetto:normal,disabledoractive
text=>STRING Displaytextstring
variable=>VARNAMEDisplaytextvariableIfthewidgetismanipulated,thevalueofthevariablewillchangeautomaticallyandifthisvariable'svalueischanged,thewidgetwillchangetoreflectthechangesinthevariable
underline=>CHAR WhichcharacterpositioninstringtounderlineThismustbeanumber0forthefirstcharacter,1forthesecondandsoon
width=>WIDTH Setshorizontalwidgetsize
wraplength=>LENGTH Wordwrappingmaximumstringlength
SomeTkCommands
BindThebindcommandassociatesPerlcodewitheventsIfyouwanttodosomethingwhentheuserdoubleclicksaiteminalistboxorwhenhe/shepressanybutton(sayF1),bindiswhatyouneedLetsbindsomethinginthenextexample
Syntax:$widget -> bind(, Callback);standsforthesequenceofbutton/mousepressesItshouldbegiveninthefollowingpatternForexampleControl+Alt+TControlandAltarethemodifiersandKeyisthetypewithtasthedetailSeethenextexampleandyouwillunderstand
#!/usr/local/bin/perluse Tk;# Main Windowmy $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 ('', sub { double() });
my $all_keys = $mw -> Label(-justify=>"left", -text=>"Press any of the followingControl+AControl+Shift+AControl+Alt+TRight clickControl+Escape") -> pack;
#Exit when the escape key is pressed$mw -> bind('', sub { exit });#Shows a helping dialog box when F1 is pressed$mw -> bind('',sub { help(); });#Binds misc keys$mw -> bind('', sub { $mw -> messageBox(-message=>"You pressed Control+A, did'nt you?")});#Control+A$mw -> bind('', sub { $mw -> messageBox(-message => "Control+Shift+A, right?"); });#Control+Shift+A$mw -> bind('', sub { $mw -> messageBox(-message => "Control, Alt and T"); });#Control+Alt+T$mw -> bind('', sub { $mw -> messageBox(-message => "The right way to click"); });#Right click$mw -> bind('', 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 functionsub help { $mw -> messageBox(-message=>"Did you ask of help?You ain't getting anyHa Ha Ha!");}
#This happens at double-clicksub double { $mw -> messageBox(-message=>"You double clicked somethingThis script is simple - so it won't display what you clicked onBut if you want a sript that is able to do that, write to me at binnyva\(at\)hotmail\(dot\)comand I will send you a better script");}
NowWhat?Perilousseascrossed,thoughtscorchingdesert,wehavecomehereafterovercomingcountlessdangerstolifeandlimbWehavereachedtheendofourquest,theendofourjourneyNowWhat?
NowyouareonyourownYoumuststrivetoachieveexcellenceinthefieldofPerl/TkprogrammingBuybooks,visitwebsites,stealcodesDoanythingtoincreaseyourknowledgeonthissubjectThereareanamazingarrayofwebsitesouttherethatwouldsupplyyouwithtutorials,programs,gamesetconPerl/TkGogetthemReadcodeofotherpeopleandstudyfromthemRemember,creativityisgreat,butplagiarismisfaster
ButthemostimportantthingprogramGetthosefingerstyping,makeprogramsinPerl/TkExperimentMake
mistakesCorrectthemThereisnobetterwayoflearningasubjectthanbydoingit
SeereferencesformorelinksonPerl/Tk
Reference
Books'MasteringPerl/Tk'bySteveLidieandNancyWalshisagoodbookthatteacheshowtocreateGraphicalUserInterfacesinPerl
LearningPerl/Tk
ProgrammingPerl'byLarryWallisthestandardbookonPerlIfyouconsiderseriousPerlprogramming,thisisamustThisisaboutPerlratherthanaboutPerl/Tk
GetMoreBooksonPerl/Tk
ManualMakeyourselffamiliarwiththemanualthatcomeswithPerlToknowmoreaboutanycommands,sayprint,justtypeperldoc -f printinthecommandpromptThisworksonbothUnixandwindowsmachinesOtherthatthat,PerlshipswithtonsofHTMLtutorialsthatteacheseverythinginperl
ExternalSitesPerl'sUsenetgroupatcomplangperltkisofgreathelptoanyPerlTkprogrammer
http://wwwperlorg/hasbeenforagestheprimaryresourcesiteformanyperldevelopers
http://learnperlorg/isasitethathasresourcesforbothbeginnersandadvancedperlprogrammers
Appendix
AppendixA:AbouttheAuthorMynameisBinnyVAIhavebeenprogramminginPerlandTcl/TkforawhilenowbutonlyrecentlyhaveIstartedprogrammingwithPerl/TkSoIamnotanexpertinPerl/TkButIhavealreadywrittenatutorialforTcl/TkSoIthoughtthatIwilltranslatetheTkpartstoperlandgivetheworldanewPerl/TkprogramSodon'tbeangryifyouseealotofsimilaritiesbetweenTcl/TkTutorialandthisPerl/TktutorialIcanplagiarisefrommyself,can'tI?Anyway,allquestions,suggestions,criticismsetccanbedirectedtobinnyva@gmailcomYoucanknowmoreaboutmeatmywebsiteForalltheprogramsthatImadeinPerl,gototheperlpageinmysite
Ifyouhavelikedthistutorial,IhavewroteanothertutorialonTcl/TklanguageCheckitoutIalsowrotetutorialsonCGIPerlandJavaScript
AppendixB:CommonlyMademistakesinPerl/TkThereareafew'irregularities'attheplaceswherePerlandTkmeetTheseplacesareoftenasourceofproblemsfornewPerl/TkprogrammersHereisalistofmostcommonmistakesmadebynewPerl/TkprogrammersImadequiteafewofthemmyself
Callbacks
CallingafunctionfromabuttonisalmostalwaystroublefortheinexperiencedAssumethatyoucreatedafunctioncalledshowGreeting$button = $mw -> Button(-text=>"Hello",-command=>showGreeting);#Won'twork$button = $mw -> Button(-text=>"Hello",-command=>showGreeting());#Again,won'twork$button = $mw -> Button(-text=>"Hello",-command=>&showGreeting);#WillnotworkThisistheporperwayofdoingit$button = $mw -> Button(-text=>"Hello",-command=>\&showGreeting);#FinallySomethingthatworks$button = $mw -> Button(-text=>"Hello",-command=>sub { showGreeting(); } );#Anothermethodofdoingit
VariablesThishasasimilareffectastheaboveproblem$entry = $mw -> Entry(-textvariable=>$var);#Thisisnottherightway$entry = $mw -> Entry(-textvariable=>\$var);#CorrectwayUsingqw//Don'tuseawhitespaceinsideavalueifyouareusingtheqw//methodtoconfigureoptionsSeebelowformoredetails
AppendixC:Tcl/TkAndPerl/TkIfyouaremoresquintedwiththeTcl/Tk'swayofdoingit,youwillbehappytoknowthatthereisawayofgivingtheoptionsintheTcl/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:CodesAlmostalltheprogramsinthetutorialareavailableinazippedformatfordownload
AppendixE:FeedBacksHowdoyoulikethistutorial?Pensomecommentsbelow
Ifyouhaveanyquestionssendmeanemailatbinnyva@gmailcomIfyouleaveaquestionintheabovefeedbackform,besuretogiveyouemailaddressifyouwantmetorespond
AppendixF:Comments
IndexAnonymousat11Mar,200804:26
HieverytimeitrytoaccessperltkmoduleitgivessegmentationfaultiusedaptgettoinstallperlandperltkmodulesAnonymousat01Jun,200810:30tryinstallingthemwithCMA
IntroductionAnshumanAtreat26Feb,200708:41Hi,
IhavejustfinishedagreattoolwithmanycommandlineoptionsItalsohasabasicCLIbaseduserinterfacetomakeitinteractive
IhappentoaowntheO'Rielly"Perl/Tk"thatIboughtforastealafewyearsago,andamconsideringaddingaGUItomytoolSoIdownloadedthePerl/TksourcecodefromCPANandfailedtocompileitusinggcconSolarisHowever,itcompiledfineonmyLinuxbox
ItriedoutafewcodesnippetsandthesearemyfirstimpressionsaboutPerl/Tk:
1Yes,it'spowerfulenoughtoprovideacoolfrontendtomytool2Thecodingseemsprettystraightforward,thoughrepeatativeandmonotonous(withlotsoftrialanderroriterations)3Theenduser,howeverwouldneedPerl/Tkinstalledonhis/herboxtoabletorunmyPerl/Tk,whichisNOTshippedbydefaultHowdoIconvincehim/hertospendagoodpartofanhourtogetPerl/Tkinstalled,sothathecanusemytool!?It'dbeeasierforhim/hertousethe(ample)commandlineoptionsIgive,orusetherudimentarytextbasedinterface
Somyquestion:IfIspendagoodpartofamonthwritingaPerl/Tkinterface,whatarethechancesthatanaverage(notaprogrammer/admin)user/operatorgetstouseit?
Thanks!BinnyVAat27Feb,200705:04Tkinterface,unfortunately,looksreallyoutdatedinlinuxsystemsHowever,inwindowssystemstheylookgreatIftowantcoollookinginterfacesinLinux,trysomethinglikeGtkforperl
MyadviceistoprovidetheGUIalongwiththeapplicationbutafterseparatingtheapplicationfromtheGUITheappshouldworkwithouttheGUIifthatishowtheuserwantsitTheGUIwillbeavalueaddMarianoat27Mar,200705:22IftheuseriscurrentlyusingaWindowsterminalyoucouldgenerateanexewithyourappinwichyoucanincludealltheusedlibraries(ieTk)
Ifnot,itmeansitisveryeasytoinstallthemoduleAnonymousat14Mar,200808:37UsePerl2Exetocompileitintoaexe,itautomaticallyincludesthePerl/Tkbinaries(Ifyouronwindows,otherwise,lullinuxfails)Useserialswstofindaserialforperl2exepurnachanderat05Jul,200708:08Hi,
I'mtryingtoaddGUItomytoolSoistartedlearningPerl/TkmoduleCanyoutellmewhereIcangetdocumentationfordifferentvaluesofanoption
Foreg,Theoption"background"isusedtosetthebackgroundcolorIknowhowtosetmybackgroundtocommoncolorslike,green,black,etcHowever,ifI'dliketochoosemyowncolorfromRGBHowcanIdoit?
Similarly,ifineedtoknowvariousvaluesavailableforanoption,whereshouldisearchfordocumentationBinnyVAat05Jul,200711:07JustsearchthenetyouwillgetPerl/TkDocswithoutmuchdifficultyForinstancePerl/TkDocumentationAnonymousat30Aug,200711:58IdonotseetheanswerinthatdocumentationI"mlookingforthepropersyntaxtospecifythecolorinRGBinsteadofacolornamepurnachander,didyoueverfindit?balajiat30Jul,200709:46hi,iscriptingatoolforvlsidesignusingperlButidontknowhowtomaketheguiforitCanuelaboratelytellmewatarallstepstobecarriedoutAnonymousat09Aug,200703:21ifiusethismethodforinstallingTk
perlMCPANeshellcpan>installBundle::CPANcpan>reloadcpancpan>installTk
iamfindingthiserrorFetchingwithLWP:wwwperlorg/CPAN/authors/id/N/NI/NIS/Tk804027targzLWPfailedwithcode[500]message[readtimeout]
cansomebodyhelpmepls!!!!!BinnyVAat09Aug,200707:04YourbestbetisjusttotryagainIthinkitisatemporaryserverissuesenthilat04Sep,200706:10hi,iamsenthilineedacodeofperltkineedtogetainputfromuserusingtheoneinputlikevisualbasicsogetvaluetoassigntheonevariablelike"$input=ccnb"
ccnbisgetfromusersenthil_v@newgenimagingcomBinnyVAat04Sep,200709:11ThedetailsareavailableintheEntrypageaflexoat11Dec,200704:07Greatsamplesintutorial!ThesejusthelpedmetounderstandthewholethingaboutPerl/TKprogramming))dswat18Dec,200708:50ThisinterfacedoesnotlookoutdatedIfyouarelookingforsomethingmorepolished,thenIsuggestyouwriteatutorialaboutusingQTOldschoolistheonlyschool:)
BinnyVAat18Dec,200711:08Unfortunately,youarerightinthecaseofLinuxTkinterfaceinLinuxisjusthorribleButitlooksrathergoodinWindowsPlusIhavenotlookedatQTyetIhavelearnedabitofGtkbutnowhereenoughtowriteatutorialPhillCat10Jan,200807:21First,thanksforagreattutorialusingPerlTKYourstyleandexamplesworkformeverywell
I'membarkingonmyfirstPerlGUIprogrammingexperienceAfterinvestigatinganumberofoptionssuchatGTK2andwxWindows,IthinkTkappealstomemostWhilethePerlTkGUIlookandfeelmaybealittleoutdated,IlikethesyntaxusedtocreateitIespeciallylikethegridpackagingsystem
I'vebeenreadingabouttheTcl::TkmodulecurrentlyavailableinCPANItseemsthatithassomeadvantagesoverPerlTK,specificallyspeedandtheabilitytousethelatestTcl/Tk85widgetssuchasTileItalsoappearstosupportPerlTKsyntax,butofcoursetherearesomedifferences
Iwaswonderingifyou'dconsideratutorialhighlightingtheTcl::TkmodulevsPerlTkdifferences,andespeciallywhichwidgetsareincludedinTcl:TkbydefaultandhowtocallexternalTclwidgetsInfact,maybejustasinglepageexplainingthesedifferencesmightbereallyuseful
Regards,Phill
BinnyVAat13Jan,200807:21I'lllookintoitbutchancesarethatIwillnotbeabletodothisstudyCurrentlyIaminWebDevelopmentIhavenotbeenactiveattheTkfrontSo,myknowledgeaboutthosesystemsareabitoutdatedAnyway,thanksforthesuggestionIwilllookintoitAnonymousat27Feb,200804:58assigningavariabletobackgroundsandthingslikethattextvariableisfortext,butIcannotfindasimilarentryforframesoranythingelseoutsideoftextinalabelIgetamessagethatsaysunknowncolorname"SCALAR(0x18a3f6c)"ifIusecodesimilarto$frame=$mw>Frame(background=>\$variable)>pack();butifIuse$frame=$mw>Frame(background=>$variable)>pack();withouttheslashthewidgetisassignedtotheonecolorpermanentlythisisasignificantproblemtomeandIwouldappreciatesomeoneelsetryingtosolvethis,becauseIhavebeenunabletofindDocsmyselftoassistmeChanioat03Mar,200805:20Iappreciateverymuchyourgreatandhonestwork!Thiscompletetutorialisaveryhelpfultoolforboth:theusersandtheperl/Tkcommunity
Wouldn'titsuitbetterifyoursitehadawikistyle?Iimagineperldocspublishedonlineinawikifashion,allfullofhyperlinks
THXS!Haveaniceyear!Alberto(Argentina)Anonymousat14Mar,200806:23FinallyfiguredouthowtospecifyrgbcolorsforwidgetsPostingithereincaseanybodyelseislooking
Puta#infrontofthe6digitrgbcodeandencloseitwithsinglequotes
Ex
background=>'#ff0000'
KumarPat03Apr,200806:45IhaveanassignmenttocreateaGUI,whichshouldbeabletoparsetheMPEGVideoBitStreamandshowusvariousproperties/semanticsoftheunderlyingvideoIsperl/TKtherightchoicefordevelopingsuchapplication?Jefffreyat04Apr,200810:35I'vestartedwritingadatabaseandpointofsalefrontendformydiveshopI'musingperlbecauseit'stheonlylanguageI'msomewhatfluentinIhaveusedTkbeforebutnotGtk2CananyonetellmeifthereisenoughinfoouttheretogetthehangofGtk2fairlyquicklyoristherealearningcurveChanioat10Apr,200808:04IfsomeonewantstogetamoreVBlikeresultwithTkyoumightwanttousethefree:ZoozGUIbuilder
ItisnotbetterthandoingitallbycodingItisjustanotherwayofcomplementingyourknowledgeofPerlTkAnd,perhaps,learningsomethingnew!
Rathnakarat21Apr,200809:41TogetGuiyoucanuseperl/TkmoduleswhichwouldgivemoreflexibilityIfounditveryusefulRefertotheexamplesinthesitetogetabetterpictureAnonymousat07May,200807:47AwonderfulltutorialthathelpedmealotandIstillkeepforreferences!
MyThanksAnonymousat20May,200812:51ThanksBinny,YouhavedoneagreatjobontheTktutorialIamactuallylookingforhelponWindows(active_state)basedTksInparticularutf8supportforTksusingforeignlanguagefontssuchasRussian,Mongolian,ChineseDoyouknowwhetherTkswillsupportutf8?Vanilla
HelloWorldAnonymousat30Jan,200705:34
couldn'tconnecttodisplay":0"at/opt/perl/lib/site_perl/582/PARISC11threadmulti/Tk/MainWindowpmline55MainWindow>new()atwelcomeplline5BinnyVAat31Jan,200704:31IhaveneverseenthiserrorbutdoyouhaveXserverrunning?TkneedsaGUIdisplayAnonymousat17Apr,200712:16youneedtosetyourdisplayenvironmentvariable,andthenalsoifyouaretelnetingandhavefurtherproblems'xhost+'fromtheoriginatingmachinefredat28Apr,200704:54Hello,
WhenIrunthehelloexampleonmywinxpboxitopensacommandpromptItstaysopenuntil
Iclosetheexample
IsthisthewayallPTKprogramswork?
ThanksBinnyVAat28Apr,200705:38YesthatshowtheyworkDon'tworryaboutitJaysonat19Jun,200703:52ldso1:/usr/local/bin/perl:fatal:libctso:openfailed:NosuchfileordirectoryPleasehelpBinnyVAat19Jun,200709:31ThereissomeissuewithyourperlinstallationsomelibrariesaremissingTrydownloadingperlandinstallingitAMPat03Aug,200708:56Probablynotaproblemw/installation,Perlismostlikelyin/usr/bin/perlinsteadAlltheLinuxdistributionsIhaveworkedonhaveitinthislocationkittuat21Jun,200708:57HIFriendsihavesomeissuesplshelpmeonthisactuallycgi/peralwithNT40environmentismovingbyLinuxanydisadvantagesandsuggestifthatisreengineeringwithjava,linuxandgivemesomepointsandpresentlyexistingsystemhaving5003wanttochangeto583soanydeprcciationididnotfindanyproblemsplshelponthatandwithlinuxhowtodeploycgi/pearlprogramsJonathanat03Aug,200703:07Kittu,CongratulationsonyourpostIhaveneverreadanythingmorecompletelyincomprehensibleplskeppupthegoodwerkuntrtanemeAnonymousat21Sep,200710:59ThanksforthetutorialBinnyIt'sverygood!Anonymousat24Nov,200708:49VeryclearandunderstandableNicetutorialThankYoutotheauthorOddChildat09May,200808:29thankyouforputtingthistogether,itwasmosthelpfulAnonymousat21May,200807:00thislineisveryslow:
$mw>messageBox(message=>"Goodbye");
Isthatsupposedtobe?Orjustmyenvironmentissue?
ThanksAnonymousat21May,200807:02MessageboxlineisveryslowIsthatsupposedtobe?Oritismyenvironmentissue?ThanksSidat21May,200809:01NewtopTk,pullingperloutofcoldstorageYourtutorialishelpfulThankyou
Widget1Anonymousat31Jul,200702:49Theexampleabovewiththefunctionpush_buttonisnotshowingthetext"whatever"Alsoifiusethecommandusestrict,howdoiwritethebaretextwhateverBinnyVAat01Aug,200706:19NoyoumisunderstoodmeThat'whatever'isnottheoutputImeantyoucanputthecodeyouwantinitsplaceOnhindsight,IthinkIshouldhavecommenteditAnonymousat31Jul,200704:31Ithinkthefunctionbody(sub)shouldbewritteninsideMainLoopitselfIhadpostedthesamequestionandIthinktheansweristhisdescription