P. 1
Tk 1Day Course Instructor Slides

Tk 1Day Course Instructor Slides

|Views: 24|Likes:
This is the instructors presentation matter for the Tk programming course, Tk Fundamentals for GUI Development, which is available online through Scribd.

The course teaches how to create simple Tk menu systems and related controls, including the following widgets: label, text, button, entry, listbox, and various dialogs.
This is the instructors presentation matter for the Tk programming course, Tk Fundamentals for GUI Development, which is available online through Scribd.

The course teaches how to create simple Tk menu systems and related controls, including the following widgets: label, text, button, entry, listbox, and various dialogs.

More info:

Categories:Types, Research
Published by: John Michael Williams on Feb 24, 2013
Copyright:Traditional Copyright: All rights reserved
List Price: $10.00 Buy Now

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
See more
See less

05/07/2015

$10.00

USD

pdf

Sections

  • Workshop Organization
  • Workshop Topics
  • Anticipated Schedule
  • TcL, Tk, and X
  • Tk Naming Conventions
  • Elementary GUI Objects
  • Window
  • Image
  • Image Creation Example
  • bitmap Image Format
  • Palette
  • Text
  • Text Example
  • Widget
  • Windows: Systems and Controls
  • Tk Window Hierarchy
  • Window Management I: tk Command
  • Window Management II: wm Command
  • wm iconbitmap Example
  • Window Management III: winfo Command
  • Geometry Management I: packer
  • packer Example
  • Geometry Management II: gridder
  • gridder Example
  • Geometry Management III: placer
  • placer Example
  • Window Stacking: raise and lower
  • Window Stacking: raise Example
  • The bitmap Image Tool
  • The mtpaint Image Tool
  • Lab 1: label Widget and icon
  • Text and Font Manipulation
  • Font Selection
  • text Widget Options I
  • text Widget Options II
  • text Widget Text Indexing
  • text Widget packing Properties I
  • text Widget packing Properties II
  • text Widget packing Properties III
  • text Widget packing Properties IV
  • entry Widget Basics
  • Event Binding
  • entry Widget Event Binding
  • entry Widget Event Binding Result
  • entry Widget Validation Options
  • entry Widget Validation Example
  • entry Widget Validation Result
  • Lab 2: GUI Text I/O
  • Image Creation and Manipulation
  • Namespace Basics
  • Image in Namespace
  • image create Subcommand
  • Other image Subcommands
  • The xbm Format
  • xbm Image Example
  • The Tk Palette
  • tk_setPalette buttons I
  • tk_setPalette buttons II
  • Command-Specific Bitmaps
  • Predefined button Bitmaps
  • A Custom button Image
  • Predefined tk_messageBox Bitmap
  • Lab 3: GUI Utility Dialogs
  • Putting Things Together
  • Independent Windows for an Application
  • labelframe Widget Example
  • labelframe Widget Result
  • The listbox Widget
  • listbox Widget Options
  • Inert listbox Example
  • Functional listbox Example (1st half)
  • Functional listbox Example (2nd half)
  • Functional listbox Result
  • tk_popup Command
  • menu Command
  • menu Command Example
  • Simple Popup GUI (Layout)
  • Simple Popup GUI (Proto. Main Window)
  • Simple Popup GUI (Prototype menu procs)
  • Simple Popup GUI (Prototype item procs)
  • Simplification of Top Menu:
  • Simplification, with Real menu Item
  • Lab 4: Image-Viewing GUI
  • Review and Wrap-Up
  • What We Presented
  • What We Omitted
  • That's It

Slides for

Tk Fundamentals for GUI Development
A Si l i con Val l ey Techni cal I nsti tute Workshop
by J ohn Michael Williams
2009-05-22
Copyright © 2009, J ohn Michael Williams.
Licensed free to Silicon Valley Technical Institute for training-course use. All
other rights reserved.
jmmwill@comcast.net
2009-05-22 Tk Workshop
List of Slides
I ntroduction and Scope.............................................................................................................................................................................................0
Workshop Organi zati on .......................................................................................................................................................................................1
Workshop Topi cs ..................................................................................................................................................................................................2
Anti ci pated Schedul e ...........................................................................................................................................................................................3
TcL, Tk, and X......................................................................................................................................................................................................4
Tk Nami ng Conventi ons ......................................................................................................................................................................................5
Elementary GUI Objects...........................................................................................................................................................................................6
Wi ndow .................................................................................................................................................................................................................7
I mage ....................................................................................................................................................................................................................8
I mage Creati on Exampl e.....................................................................................................................................................................................9
bi tmap I mage Format ........................................................................................................................................................................................10
Pal ette.................................................................................................................................................................................................................11
Text .....................................................................................................................................................................................................................12
Text Exampl e .....................................................................................................................................................................................................13
Wi dget.................................................................................................................................................................................................................14
Windows: Systems and Controls ...........................................................................................................................................................................15
Tk Wi ndow Hi erarchy........................................................................................................................................................................................16
Wi ndow Management I : tk Command .............................................................................................................................................................17
Wi ndow Management I I : wm Command .........................................................................................................................................................18
wm i conbi tmap Exampl e ...................................................................................................................................................................................19
Wi ndow Management I I I : wi nfo Command ....................................................................................................................................................20
Geometry Management I : packer ....................................................................................................................................................................21
packer Exampl e..................................................................................................................................................................................................22
Geometry Management I I : gri dder ..................................................................................................................................................................23
gri dder Exampl e.................................................................................................................................................................................................24
Geometry Management I I I : pl acer ..................................................................................................................................................................25
pl acer Exampl e...................................................................................................................................................................................................26
Wi ndow Stacki ng: rai se and l ower ...................................................................................................................................................................27
Wi ndow Stacki ng: rai se Exampl e ....................................................................................................................................................................28
The bi tmap I mage Tool ......................................................................................................................................................................................29
The mtpai nt I mage Tool ....................................................................................................................................................................................30
Lab 1: l abel Widget and icon .................................................................................................................................................................................31
Text and Font Manipulation ..................................................................................................................................................................................32
2009-05-22 Tk Workshop
Font Sel ecti on.....................................................................................................................................................................................................33
text Wi dget Opti ons I .........................................................................................................................................................................................34
text Wi dget Opti ons I I .......................................................................................................................................................................................35
text Wi dget Text I ndexi ng.................................................................................................................................................................................36
text Wi dget packi ng Properti es I ......................................................................................................................................................................37
text Wi dget packi ng Properti es I I .....................................................................................................................................................................38
text Wi dget packi ng Properti es I I I ...................................................................................................................................................................39
text Wi dget packi ng Properti es I V....................................................................................................................................................................40
entry Wi dget Basi cs ...........................................................................................................................................................................................41
Event Bi ndi ng ....................................................................................................................................................................................................42
entry Wi dget Event Bi ndi ng .............................................................................................................................................................................43
entry Wi dget Event Bi ndi ng Resul t..................................................................................................................................................................44
entry Wi dget Val i dati on Opti ons ......................................................................................................................................................................45
entry Wi dget Val i dati on Exampl e ....................................................................................................................................................................46
entry Wi dget Val i dati on Resul t ........................................................................................................................................................................47
Lab 2: GUI Text I / O ..............................................................................................................................................................................................48
I mage Creation and Manipulation.........................................................................................................................................................................49
Namespace Basi cs ..............................................................................................................................................................................................50
I mage i n Namespace..........................................................................................................................................................................................51
i mage create Subcommand................................................................................................................................................................................52
Other i mage Subcommands ..............................................................................................................................................................................53
The xbm Format.................................................................................................................................................................................................54
xbm I mage Exampl e ..........................................................................................................................................................................................55
The Tk Pal ette....................................................................................................................................................................................................56
tk_setPal ette buttons I ......................................................................................................................................................................................57
tk_setPal ette buttons I I .....................................................................................................................................................................................58
Command-Speci fi c Bi tmaps ..............................................................................................................................................................................59
Predefi ned button Bi tmaps ...............................................................................................................................................................................60
A Custom button I mage.....................................................................................................................................................................................61
Predefi ned tk_messageBox Bi tmap ..................................................................................................................................................................62
Lab 3: GUI Utility Dialogs ....................................................................................................................................................................................63
Putting Things Together .........................................................................................................................................................................................64
I ndependent Wi ndows for an Appl i cati on ........................................................................................................................................................65
l abel frame Wi dget Exampl e ..............................................................................................................................................................................66
l abel frame Wi dget Resul t ..................................................................................................................................................................................67
The l i stbox Wi dget .............................................................................................................................................................................................68
l i stbox Wi dget Opti ons.......................................................................................................................................................................................69
I nert l i stbox Exampl e ........................................................................................................................................................................................70
2009-05-22 Tk Workshop
Functi onal l i stbox Exampl e (1st hal f)...............................................................................................................................................................71
Functi onal l i stbox Exampl e (2nd hal f) .............................................................................................................................................................72
Functi onal l i stbox Resul t...................................................................................................................................................................................73
tk_popup Command ...........................................................................................................................................................................................74
menu Command .................................................................................................................................................................................................75
menu Command Exampl e .................................................................................................................................................................................76
Si mpl e Popup GUI (Layout)..............................................................................................................................................................................77
Si mpl e Popup GUI (Proto. Mai n Wi ndow) .......................................................................................................................................................78
Si mpl e Popup GUI (Prototype menu procs).....................................................................................................................................................79
Si mpl e Popup GUI (Prototype i tem procs).......................................................................................................................................................80
Si mpl i fi cati on of Top Menu: ..............................................................................................................................................................................81
Si mpl i fi cati on, wi th Real menu I tem................................................................................................................................................................82
Lab 4: I mage-Viewing GUI ....................................................................................................................................................................................83
Review and Wrap-Up..............................................................................................................................................................................................84
What We Presented ...........................................................................................................................................................................................85
What We Omi tted ..............................................................................................................................................................................................86
That's I t. ..................................................................................................................................................................................................................87
I ntroducti on and Scope
2009-05-22 Tk Workshop Sl i de 1
Workshop Organization
Thi s i s a hands-on workshop.
Lecture and l ab al ternate:
◊ Pl ease i nterrupt duri ng l ecture i f confused.
◊ Pl ease save specul ati on or el aborati on for l ab ti me or break.
◊ Break any ti me duri ng l ab.
◊ No cel l phone (or other computer) use duri ng l ecture.
2009-05-22 Tk Workshop Sl i de 2
Workshop Topics
Attendees are assumed to know TcL; there i s no TcL i nstructi on i ncl uded.
Emphasized topi cs are covered most thoroughl y; others more l i ghtl y:
Tk wi dget overvi ew
image creation
X11 bitmap (xbm) management
the Tk pal ette
Tk GUI database col ors
font sel ecti on
text I/O and entry validation
Tk integration with TcL scripts
Tk naming conventions
window systems and namespaces
elementary window creation and control
geometry managers:
packer, gri dder, pl acer
bitmap and mtpaint uti l i ti es
wi dgets and uti l i ty di al og templ ates:
label, text, entry, button, frame,
tk_messageBox, tk_dialog, listbox,
tk_popup, and others
2009-05-22 Tk Workshop Sl i de 3
Anticipated Schedule
9:00 - 10:00
I ntroducti on; wi dgets and wi ndow systems
10:00 - 10:30
Lab 1: A label wi th i con
10:30 - 11:30
Text and font mani pul ati on
11:30 - 12:00
Lab 2: Text I /O
12:00 - 12:30
Lunch (provi ded)
12:30 - 13:30
Lab 2 (concl uded)
13:30 - 14:00
I mage creati on and mani pul ati on
14:00 - 15:30
Lab 3: Tk uti l i ty templ ates
15:30 - 16:00
Wi ndow desi gn and control
16:00 - 17:15
Lab 4: A si mpl e GUI appl i cati on
17:15 - 17:30
Revi ew and wrap-up
2009-05-22 Tk Workshop Sl i de 4
TcL, Tk, and X
Tk i s a TcL package (col l ecti on) of TcL commands.
Tk commands control the OS graphi cal UI by runni ng compi l ed
programs i n .so l i brary fi l es (Li nux) or .dll's (Wi ndows).
The wi dgets and opti ons of Tk are deri ved from si mi l ar ones i n the
nati ve Li nux X11 wi ndow system.
The Tk wi sh shel l automati cal l y creates an X wi ndow hi erarchy
rooted i n a wi ndow named '.'.
2009-05-22 Tk Workshop Sl i de 5
Tk Naming Conventions
Wi ndow and command names must be uncapi tal i zed.
Command names created of more el ementary names fol l ow thi s rul e:
• Fi rst el ement uncapi tal i zed.
• Al l other el ements uncapi tal i zed unl ess fi rst el ement i s "tk_".
• I f fi rst el ement i s "tk_", second el ement i s uncapi tal i zed, and al l
subsequent el ements are capi tal i zed.
Exampl es:
menubutton
toplevel
tk_messageBox
tk_getOpenFile
2009-05-22 Tk Workshop Sl i de 6
El ementary GUI Obj ects
window
image
bitmap
palette
text
widget
2009-05-22 Tk Workshop Sl i de 7
Window
Wi ndow: A rectangul ar area of any si ze or appearance.
Associ ates the screen wi th the appl i cati on; defi nes a Tk executabl e object.
Everythi ng i n Tk begi ns wi th a wi ndow i n a TcL scri pt.
Wi ndow name must not be capi tal i zed!
proc prompt3Ans { WName B0 B1 B2 } \
{
set Choice \
[tk_dialog .$WName Question {Say What?} question 0 $B0 $B1 $B2];
#
switch $Choice \
{ 0 { puts "Choice was $B0"; }
1 { puts "Choice was $B1"; }
2 { puts "Choice was $B2"; }
default { puts "Choice=$Choice UNKNOWN. Prompt3Ans() failure?"; }
}
return $Choice;
}
prompt3Ans x hello goodbye wait;
2009-05-22 Tk Workshop Sl i de 8
Image
Two ki nds. May be any si ze.
• bitmap. Monochrome i n xbm format. Col ors programmabl e.
• photo. 32-bi t col or i n any common format (not i n thi s Workshop).
Decl ared by the Tk image create command.
There al so exi st icons. Smal l "i mages".
• Monochrome i n xbm format. Col ors automati c.
• Di spl ayed i n wi ndow banner or desktop control bar, onl y.
• I n Wi ndows, opti onal l y i n ico (programmabl e mul ti col or) format.
Decl ared by the Tk wm iconbitmap command.
2009-05-22 Tk Workshop Sl i de 9
Image Creation Example
image create bitmap Lever_Bitmap -file Lever_Bitmap.xbm;
set Msg "Lever Action Illustrated";
pack [label .z -textvariable Msg -font {-family Courier -size 24 \
-weight bold} -compound bottom -image Lever_Bitmap -bg white];
2009-05-22 Tk Workshop Sl i de 10
bitmap Image Format
The xbm format i s ASCI I characters, i n C programmi ng l anguage.
May be created and stored i n TcL stri ng; usual l y stored i n a di sc fi l e.
#define x_width Wpix /* Wpix pixels wide */
#define x_height Hpix /* Hpix pixels high */
static char x_bits[]
= { 0xnn, ... (one hex byte per 8 pixels) ..., 0xnn };
Each n represents a hex nybbl e wi th val ue between 0 (= bi nary 0000) and f
(= bi nary 1111). x i s arbi trary name from the xbm fi l e creator.
We'l l l ook at thi s format agai n l ater.
2009-05-22 Tk Workshop Sl i de 11
Palette
Tk comes wi th a defaul t 256-col or pal ette defi ned i n RGB components whi ch
i s appl i ed to al l non-i mage graphi cs.
# R G B
...
green4 0 139 0
GreenYellow 173 255 47
grey 190 190 190
grey0 0 0 0
grey1 3 3 3
grey2 5 5 5
...
slate blue 106 90 205
slate gray 112 128 144
...
The tk_setPalette command determi nes the GUI col or styl e wherever
programmed col ors are used.
Wi dgets are assi gned di fferent col ors areas i n thei r foreground vs. background areas.
Wi dget col ors al so may depend on programmed sel ecti on state or hi ghl i ghti ng.
We shal l l ook i nto tk_setPalette l ater.
2009-05-22 Tk Workshop Sl i de 12
Text
Defi ned by TcL stri ng.
Character appearance from font opti ons:
• proporti onal vs. monospace
• seri f vs. sans-seri f
• si ze i n poi nts (1 poi nt ~= 1/3 mm)
• wei ght = normal vs. bol d
• sl ant = roman vs. i tal i ci zed
• underl i ned
• overstri ked
Defaul t = proporti onal , sans-seri f, 12-pt, normal , roman.
= Helvetica.
2009-05-22 Tk Workshop Sl i de 13
Text Example
proc fontLabel { Win Options } \
{
upvar $Options MsgL; # *L for local reference variable.
set Opts [join $MsgL];
pack [label .$Win -text "$MsgL" -fg black -bg {light green} \
-font $Opts];
}
set Msg1 {-family Courier -size 14 -weight bold -slant roman};
set Msg2 {-family Helvetica -size 16 -weight bold -slant italic};
set Msg3 {-family Times -size 18 -weight normal -slant roman};
#
# wish runtime:
fontLabel x Msg1;
fontLabel y Msg2;
fontLabel z Msg3;
2009-05-22 Tk Workshop Sl i de 14
Widget
A graphi cal object.
Not a wi ndow, but i mpl emented i n a wi ndow.
Graphi cal gadget pai red wi th speci al i zed functi onal i ty.
Exampl es:
• label
• text
• tk_messageBox
• tk_dialog
• button
2009-05-22 Tk Workshop Sl i de 15
Wi ndows: Systems and Control s
Wi ndow Hi erarchy
Wi ndow Management Commands
Geometry Managers
The wish shel l
2009-05-22 Tk Workshop Sl i de 16
Tk Window Hierarchy
Appl i cati on: A si ngl e scri pt executed by wish.
Wi ndows: Created by an appl i cati on; exi st i n a hi erarchy.
Root of wi ndow hi erarchy i s named '.' i n the scri pt.
Every wi ndow i n that appl i cati on must have a di fferent name.
Subordi nate wi ndow l evel s i n a hi erarchi cal path are separated by '.'.
Exampl es:
label . -text "Hello"; # ERROR: Can't name a new window after .
label .x -text "Hello"; # New window named x in .
label .x.yWin -text "SubHello"; # New window named yWin in x
2009-05-22 Tk Workshop Sl i de 17
Window Management I: tk Command
tk appname. Returns or modi fi es the appl i cati on name. Exampl e:
proc setAppName { Win Msg {App argv0} } \
{
upvar $App AppL;
tk appname $AppL;
pack [label .$Win -text "$Msg" -fg white -bg {dark blue} \
-font {-family Times -size 14 -weight bold -slant italic}];
}
set Msg "This is an example of $argv0";
set NewName "newAppName";
setAppName x $Msg NewName;
By defaul t, a banner wi l l say "wish", the name of the appl i cati on runti me.
Li ke a wi ndow or proc, an application name must not be capi tal i zed.
tk windowingsystem. For scri pt portabi l i ty. Returns x11 or win32.
2009-05-22 Tk Workshop Sl i de 18
Window Management II: wm Command
Control s the Tk wi ndow manager.
wm iconbitmap. The onl y way to associ ate an i con wi th a wi ndow. An
i coni fi ed wi ndow i s a wm affai r, not an image affai r!
Names a top-l evel wi ndow and a bi tmap defi ni ti on:
wm iconbitmap topwindow_path @fname.xbm
I n Wi ndows, onl y, thi s syntax i s al l owed:
wm iconbitmap topwindow_path ?-default? fname.ico
(exampl e next sl i de).
wm state. Two useful opti ons: normal and iconic.
wm title. Assi gns a text stri ng ti tl e to a wi ndow banner. Doesn't change
appl i cati on name.
2009-05-22 Tk Workshop Sl i de 19
wm iconbitmap Example
proc setAppName { Win Msg {App argv0} } \
{
upvar $App AppL;
tk appname $AppL;
set L [label .$Win -text "$Msg" -fg white -bg {dark blue} -font {-family \
Times -size 16 -weight normal -slant italic}];
pack $L;
if { [tk windowingsystem]=="x11" } \
{ wm iconbitmap . @TkIconBWneg.xbm; } \
else { wm iconbitmap . TkIcon.ico; }
}
set Msg "This is an example of $argv0";
set NewName "newAppName";
#
setAppName x $Msg NewName;
Run i n wish i n
Wi ndows:
I n Li nux:
2009-05-22 Tk Workshop Sl i de 20
Window Management III: winfo Command
winfo exists. Reports whether a wi ndow path exi sts.
winfo geometry. Reports the width x height i n number of pi xel s of a
wi ndow.
winfo id. Reports the l ow-l evel (32-bi t) handl e used by the operati ng
system to i denti fy a wi ndow.
winfo pathname. Reports the Tk pathname of a wi ndow, gi ven i ts l ow-l evel
handl e (i d).
winfo manager. Reports the name of the wi ndow geometry manager
command for a wi ndow. Thi s may be grid, pack, or place.
Geometry managers determi ne wi dget l ayout wi thi n a wi ndow.
2009-05-22 Tk Workshop Sl i de 21
Geometry Management I: packer
The pack command al l ocates wi ndow parcel s sequenti al l y and
uni di mensi onal l y.
Scri pt can speci fy:
• the wi ndow starti ng si de (-side).
• the wi dget al i gnment i n i ts parcel (-anchor).
• a sequenti al i nserti on poi nt (-before; -after).
• a subwi ndow i n whi ch to pack the wi dget (-in).
pack info reports al l opti ons i n effect.
2009-05-22 Tk Workshop Sl i de 22
packer Example
proc showPacker1 { } \
{wm title . {Default Pack};
# Create the windows:
foreach n {1 2 3 4} \
{set L$n [label .x$n -text "Win .x$n" -font "-size [expr 12+(4*$n)]"];}
# Call the geometry manager:
foreach n {1 2 3 4} { pack [subst \$L$n]; }
# Append the pack info reports:
foreach n {1 2 3 4} \
{ set M$n "[subst \$L$n]: [pack info ".x$n"]";
pack [label ".y$n" -text [subst \$M$n] -font {-size 12 \
-family Times}];
}
}
showPacker1;
2009-05-22 Tk Workshop Sl i de 23
Geometry Management II: gri dder
The grid command al l ocates wi ndow parcel s two-di mensi onal l y.
Scri pt can speci fy:
• the wi dget wi ndow row (-row).
• the wi dget wi ndow col umn (-column).
• mul ti row or mul ti col umn parcel s (-rowspan; -columnspan).
• a subwi ndow i n whi ch to pack the wi dget (-in).
• expansi on of a smal l wi dget to fi l l i ts parcel (-sticky).
grid configure modi fi es opti ons previ ousl y speci fi ed.
grid info reports al l opti ons i n effect.
2009-05-22 Tk Workshop Sl i de 24
gri dder Example
proc showGridder { } \
{
wm title . {All One Grid Row};
# Create the windows:
foreach n {1 2 3 4} \
{set L$n [label .x$n -text "Win .x$n" -font "-size [expr 12+(4*$n)]"];}
# Call the geometry manager:
foreach n {1 2 3 4} { grid [subst \$L$n] -row 0 -column [expr $n - 1]; }
# Append the grid info reports, configured horizontally:
foreach n {1 2 3 4} \
{ set M$n "[subst \$L$n]: [grid info .x$n]";
grid configure [label ".y$n" -text [subst \$M$n] \
-font {-size 12 -family Times}] -columnspan 4 ;
}
}
showGridder;
2009-05-22 Tk Workshop Sl i de 25
Geometry Management III: pl acer
The place command speci fi es l ayout of one wi ndow i n one other.
Scri pt can speci fy:
• the wi ndow i n whi ch to pl ace the second wi ndow (-in).
• the poi nt of reference for l ocati on opti ons (-anchor).
• the fracti onal rel ati ve l ocati on of the second wi ndow (-relx; -rely).
• the rel ati ve l ocati on i n pi xel s of the second wi ndow (-x; -y).
• the fracti onal rel ati ve hei ght and wi dth (-relheight; -relwidth).
• the hei ght and wi dth i n pi xel s (-height; -width).
place configure modi fi es opti ons previ ousl y speci fi ed.
place info reports al l opti ons i n effect.
2009-05-22 Tk Workshop Sl i de 26
pl acer Example
proc showPlacePairs { } \
{wm title . {Two Paired Labels};
# Create the windows:
foreach n {1 2 3 4} \
{label .x$n -text "Win .x$n" -font "-size [expr 12+(4*$n)]" -bg white;}
# Call the geometry manager:
place .x1 -relheight 0.125 -relx 0.4 -rely 0.01;
place .x2 -relheight 0.125 -relx 0.1 -rely 0.01;
place .x3 -in .x1 -relheight 1.0 -relx 1.0 -rely 0;
place .x4 -in .x2 -relheight 2.0 -relx 1.0 -rely 1.0;
# Append the place info reports:
foreach n {1 2 3 4} \
{set M$n ".x$n: [place info .x$n]";
label ".y$n" -text [subst \$M$n] -font {-size 12 \
-family Times} -bg {light green};
place .y$n -relheight 0.125 -relx 0.0 -rely [expr 0.4+($n-1)/8.0];
}
}
showPlacePairs;
The showPlacePairs() di spl ay, i nteracti vel y stretched hori zontal l y and compressed verti cal l y.
2009-05-22 Tk Workshop Sl i de 27
Window Stacking: raise and lower
Stacki ng order matters where wi ndows overl ap.
Wi ndows wi th hi gher stacki ng order may conceal ones whi ch are l ower.
• raise i ncreases stacki ng order.
• lower decreases stacki ng order.
Defaul t i s to bri ng wi ndow to top (or bottom) of enti re stack.
Opti onal l y, a wi ndow may be speci fi ed rel ati ve to whi ch the raise or
lower wi l l be done.
See Workbook for exampl es.
2009-05-22 Tk Workshop Sl i de 28
Window Stacking: raise Example
I n a Textbook exampl e of placer, the ori gi nal wi ndow arrangement was wi th wi ndow
.x4 on top, and wi th .x2 above .x1, as fol l ows:
After runni ng "raise .x1 .x2" and then "raise .x3", the resul t was:
2009-05-22 Tk Workshop Sl i de 29
The bi tmap Image Tool
2009-05-22 Tk Workshop Sl i de 30
The mtpai nt Image Tool
2009-05-22 Tk Workshop Sl i de 31
Lab 1: label Wi dget and i con
2009-05-22 Tk Workshop Sl i de 32
Text and Font Mani pul ati on
Fonts
The text Wi dget
The entry Wi dget
2009-05-22 Tk Workshop Sl i de 33
Font Selection
Tk font al ways al l ows these opti ons, for any wi dget:
-family
The defaul t general l y i s a sans-seri f font cl ose i n
appearance to Hel veti ca.
-size
The defaul t usual l y i s somewhere near 12-poi nt on the
screen di spl ayed.
-weight
Al ternati ves are normal (the defaul t) and bold.
-slant
Al ternati ves are roman (unsl anted; the defaul t) and
italic.
-underline Wi ndows onl y. A bool ean; the defaul t i s false.
-overstrike Wi ndows onl y. A bool ean; the defaul t i s false.
Seri f: A cross-stroke at the end of some character strokes.
For exampl e, the 'S' on the l eft i s seri fed; the
one on the ri ght i s sans-seri f:
2009-05-22 Tk Workshop Sl i de 34
text Widget Options I
Exampl e procedure to show text opti ons:
proc showText {Win Wid Points} \
{
wm title . "Text .$Win width=$Wid; $Points pt";
# Define the widget:
text .$Win -font "-size $Points -family Times" -height 1 \
-width $Wid;
.$Win insert end "Hello. ";
.$Win insert end "A text String!";
#
# Display it with geometry defaults:
pack .$Win;
}
2009-05-22 Tk Workshop Sl i de 35
text Widget Options II
1
showText x 10 24;
2 (#1, stretched interactively)
3
showText x 20 24;
4
showText x 20 12;
(stretched interactively)
5
showText x 20 24;
6
showText x 20 24;
(height = 2)
2009-05-22 Tk Workshop Sl i de 36
text Widget Text Indexing
I n a Tk text wi dget, use lineNo.charIndex
Li ne numbers start at 1; char i ndi ces start at 0.
Exampl e (see Workbook for ful l exampl e):
proc showFrameText { WF WTop WTxt } \
{... $WTextPath defined ...
text .$WTextPath -font "-size 16 -family Times" -height 2 -width 45;
.$WTextPath insert end "Hello. \$FrameID=$FrameID.\n" ;
.$WTextPath delete 1.5;
.$WTextPath insert 1.5 " from a text string!";
.$WTextPath insert 2.0 "frame=.$WF; toplevel=.$WTop; text=.$WTextPath.";
...
}
2009-05-22 Tk Workshop Sl i de 37
text Widget packing Properties I
Si mpl e copy of a stri ng from a text wi dget to a label wi dget:
proc getTextToLabel { Win Txt } \
{wm title . {Text Get and Put Into Label};
# Initialize the text widget:
text .$Win -font "-size 16 -family Times" -height 2 -width 40;
.$Win insert end "$Txt\n" ;
# Get the first line of text and print it in a label:
set LabelMsg [.$Win get 1.0 1.end];
label .x$Win -text $LabelMsg -font {-size 24} -bg pink -fg black;
# Display the text and label together:
pack .$Win .x$Win;
}
getTextToLabel t "Hello Cruel World!";
2009-05-22 Tk Workshop Sl i de 38
text Widget packing Properties II
Usi ng destroy to avoi d wi ndow name confl i cts:
proc textIO_Destroy { Win Txt } \
{if { [winfo exists .$Win] } { destroy .$Win .x$Win; }
wm title . {Text Replace with Destroy};
# Initialize the text widget:
text .$Win -font "-size 16 -family Times" -height 2 -width 40;
.$Win insert end "$Txt\n" ;
# Get the first line of text and print it in a label:
set LabelMsg [.$Win get 1.0 1.end];
label .x$Win -text $LabelMsg -font {-size 24} \
-bg pink -fg black -height 2 -anchor n;
# Display the text and label together:
pack .$Win .x$Win;
}
set Msg "Hello Cruel World!";
textIO_Destroy t $Msg; # Initial display.
set Msg "2nd $Msg";
after 2000 { textIO_Destroy t $Msg; }; # Delayed display.
I ni ti al l y: After two seconds:
2009-05-22 Tk Workshop Sl i de 39
text Widget packing Properties III
Appendi ng text, wi thout destroy (see Workbook for ful l exampl e):
proc textIO_SameWin { Win Txt } \
{...
if { ![winfo exists .$Win] } { text .$Win ... }
.$Win insert end "$Txt\n" ;
# Get the first line of text and print it in a label:
set LabelMsg [.$Win get 1.0 1.end];
if { ![winfo exists .x$Win] } { label .x$Win -text $LabelMsg ... }
pack .$Win .x$Win;
}
set Msg "Hello Cruel World!";
textIO_SameWin t $Msg;
set Msg "2nd $Msg";
after 2000 { textIO_SameWin u $Msg; }
I ni ti al l y: After two seconds:
2009-05-22 Tk Workshop Sl i de 40
text Widget packing Properties IV
See the Workbook "Order of Creati on Effect" for compl ete exampl e:
...
after 2000 {
set Msg "2nd $Msg"; textIO_AppSupp t $Msg;
set Msg "3rd $Msg"; textIO_AppSupp u $Msg;
}
...
after 2000 {
set Msg "3rd $Msg"; textIO_AppSupp u $Msg;
set Msg "2nd $Msg"; textIO_AppSupp t $Msg;
}
2009-05-22 Tk Workshop Sl i de 41
entry Widget Basics
A text wi dget i s for di spl ayi ng and edi tti ng text.
An entry wi dget i s to provi de requi red text i nput for the GUI .
The text and entry wi dgets work the same way, except:
• entry i s al ways 1-l i ne stri ng; NL i nput i s i gnored.
• entry get can return onl y the enti re stri ng.
• entry i ncl udes bui l t-i n syntax val i dati on.
2009-05-22 Tk Workshop Sl i de 42
Event Binding
Event binding can cause a wi sh scri pt to be executed repeatedl y.
The bind l asts as l ong as the wi ndow.
Any proc can be binded; bindi ng makes sense when the proc control s
an entry or other i nteracti ve wi dget.
The most useful event bindi ngs:
bind Keyword Event Description
Key
Any acti vati on of a keyboard key
KeyPress
Depressi on of a keyboard key
KeyRelease
Rel ease of a depressed keyboard key
Button
Any acti vati on of a mouse button
ButtonPress
Depressi on of a mouse button
ButtonRelease
Rel ease of a depressed mouse button
Motion
Any moti on of the mouse cursor i n the wi ndow
contai ni ng the entry
NOTE: Bug! I n some Li nux versi ons, <Key> works the way that <Motion> or <Button> shoul d!
2009-05-22 Tk Workshop Sl i de 43
entry Widget Event Binding
proc doSimpleEntry { Win } \
{wm title . {Simple Entry Into Label};
global Txt; # See the Workbook on why this isn't an upvar!
#
if { [winfo exists .$Win] } \
{ set Txt [.$Win get]; } \
else {entry .$Win -font {-size 14 -family Times} -width 30;
# Initialize the text:
.$Win insert end $Txt;
pack .$Win;
}
# The label:
if { ![winfo exists .x$Win] } \
{label .x$Win -textvariable Txt -bg yellow -fg black \
-font {-size 16 -family Courier -weight bold};
pack .x$Win;
}
}
set Txt "Enter text here: ";
doSimpleEntry t;
bind . <Key> {doSimpleEntry t};
2009-05-22 Tk Workshop Sl i de 44
entry Widget Event Binding Result
The i ni ti al resul t of runni ng the
above scri pt i n wish i s the stri ng
provi ded before the proc cal l :
The l abel i nteracti vel y i s updated as we enter some new text at
the keyboard.
The get i n the binded scri pt makes
i t responsi ve to al l keyboard entry
edi ts. Here i s the resul t of
backspaci ng from the keyboard over
most of the previ ous text:
2009-05-22 Tk Workshop Sl i de 45
entry Widget Validation Options
Database Name Purpose and Command Syntax
validate
Sets the val i dati on mode:
-validate mode
validateCommand
Speci fi es the val i dati on command:
-validatecommand cmdName
invalidCommand
Speci fi es the command to run on val i dati on false:
-invalidcommand cmdName
The val i dati on modes are as fol l ows:
none Val i dati on i s di sabl ed (the defaul t).
key Every keyboard event tri ggers a val i dati on.
focus Any change i n entry wi ndow focus tri ggers val i dati on.
focusin Val i dati on i s tri ggered whenever the entry gai ns the focus.
focusout Val i dati on i s tri ggered whenever the entry l oses the focus.
all Any keyboard or focus event tri ggers val i dati on.
2009-05-22 Tk Workshop Sl i de 46
entry Widget Validation Example
proc getInteger { Win } \
{wm title . {entry Integer Validation};
global UserInt;
proc val_getInteger {Win} \
{global UserInt;
if {[string is integer -strict $UserInt]&&[string length $UserInt]==2} \
{tk_dialog .v$Win "SUCCESS" \
"Very good: $UserInt is valid." {} 0 "Dismiss" ;
return 1;
} else {return 0;}
}
proc inval_getInteger {Win} \
{bell;
tk_dialog .i$Win "ERROR" "Value must be a 2-digit integer.\nTry again." \
{} 0 "Dismiss";
return 1;
}
if { [winfo exists .$Win] } \
{ set UserInt [.$Win get]; } \
else { entry .$Win -font {-size 18 -family Courier} -width 20 \
-validate focusout -vcmd "val_getInteger $Win"\
-invcmd "inval_getInteger $Win";
pack .$Win;
}
}
set IWin "iIn"; # Window names must be uncapitalized.
getInteger $IWin;
bind . <Key> "getInteger $IWin";
2009-05-22 Tk Workshop Sl i de 47
entry Widget Validation Result
The entry awai ts i nput thi s way:
I f "OK" i s entered by mi stake,
I f "19" i s entered,
2009-05-22 Tk Workshop Sl i de 48
Lab 2: GUI Text I /O
2009-05-22 Tk Workshop Sl i de 49
I mage Creati on and
Mani pul ati on
Namespace for I mages
The image Command
X11 Bi tmaps (xbm)
The Tk Pal ette
Wi dget-speci fi c Bi tmaps
2009-05-22 Tk Workshop Sl i de 50
Namespace Basics
namespace eval NamespaceName { ... };
namespace exists NamespaceName;
variable command repl aces the set command.
procs or vari abl es can be referenced hi erarchi cal l y:
variable LocalVar $NamespaceName1::VariableName;
variable NamespaceName::VariableName [TcL command];
NamespaceName::procName procArglist
2009-05-22 Tk Workshop Sl i de 51
Image in Namespace
Decl ared image names are gl obal ; so, use mangl ed i mage names; or, put
i mages i n a namespace.
namespace eval iSpace {
variable LeverImage \
[image create bitmap LeverImage -file Lever_Bitmap.xbm];
}
proc labelNamespace { Win Img } \
{wm title . {Label with Image in iSpace};
label .q$Win -text "This Image is in iSpace" -font {-size 24} \
-compound top -image $Img -bg {light blue};
pack .q$Win ;
}
labelNamespace x $iSpace::LeverImage;
2009-05-22 Tk Workshop Sl i de 52
image create Subcommand
Syntax:
image create type ?name? ?type_options?;
Returns the i mage name.
Type must be bitmap or photo.
The name i s opti onal , but i t shoul d be speci fi ed.
The i mage name si l entl y wi l l repl ace a preexi sti ng i mage of the same
name, a proc, vari abl e, or anythi ng el se i n scope.
Bi tmap type opti ons i ncl ude background and foreground col ors for the
i mage bi t-map (-file Fname or -data String) and mask-map (-
maskfile or -maskdata).
2009-05-22 Tk Workshop Sl i de 53
Other image Subcommands
image delete Name. Undecl ares an i mage name.
image names. Returns a l i st of al l i mage names i n scope.
2009-05-22 Tk Workshop Sl i de 54
The xbm Format
Pure ASCI I text; C l anguage.
#define xIcon_width 64
#define xIcon_height 64
static char xIcon_bits[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0,
... (omitted) ..., 0xff, 0xff,
};
Byte pattern i s unrol l ed from l eft to ri ght, LSB to MSB:
0xe0 represents 00000111 (5 background bi ts fol l owed by 3 foreground).
2009-05-22 Tk Workshop Sl i de 55
xbm Image Example
proc doBitmap { Win Fname } \
{
wm title . "Bitmap from $Fname";
image create bitmap xImage$Win -file $Fname -ba red -fo yellow;
pack [label .$Win -image xImage$Win -width 300 -bg white];
}
doBitmap x xIcon.xbm
2009-05-22 Tk Workshop Sl i de 56
The Tk Palette
Defaul t pal ette has 256 col ors, many named.
Defi ned i n RGB (Red-Green-Bl ue) components (8 x 3 = 24 bi ts).
# R G B
...
green4 0 139 0
GreenYellow 173 255 47
grey 190 190 190
grey0 0 0 0
grey1 3 3 3
grey2 5 5 5
...
slate blue 106 90 205
slate gray 112 128 144
...
The tk_setPalette command determi nes the GUI col or styl e. Appl i es to:
foreground
activeForeground
selectForeground
disabledForeground
selectColor
highlightColor
background
activeBackground
selectBackground
highlightBackground
insertBackground
troughColor
2009-05-22 Tk Workshop Sl i de 57
tk_setPalette buttons I
proc doColors { Win Fname } \
{
wm title . "C00";
image create bitmap bm$Win -file $Fname;
text .x$Win -height 1 -width 4 -font {-size 20};
.x$Win insert end "XYZ";
#
button .bt1$Win -text "B1" -default normal;
button .bt2$Win -text "B2" -default active;
button .bt3$Win -text "B3" -default disabled;
#
pack [label .$Win -image bm$Win -width 100] -side left;
pack .x$Win .bt1$Win .bt2$Win .bt3$Win -side left;
}
tk_setPalette white; # Default = background, only.
doColors x xIcon.xbm
After sweepi ng the cursor
to sel ect 'Z', the B1 button
was hel d depressed.
2009-05-22 Tk Workshop Sl i de 58
tk_setPalette buttons II
tk_setPalette Arguments Image Displayed
background white foreground #5050ff;
background white selectForeground #5050ff;
background white selectBackground #5050ff;
background white activeBackground #5050ff;
background white insertBackground #5050ff;
See the Workbook for other opti ons.
2009-05-22 Tk Workshop Sl i de 59
Command-Specific Bitmaps
Two di fferent, generi c Tk wi dget graphi cs:
-image = an xbm i mage.
-bitmap = a predefi ned i mage wi th a reserved name.
Predefi ned -bitmap i mages are:
error
A ci rcl e, stri cken out.
hourglass
An hourgl ass graphi c.
info
A capi tal I .
questhead
Profi l e si l houette of a head wi th questi on mark for brai n.
question
A questi on mark.
warning
An excl amati on poi nt (often i n a tri angl e).
2009-05-22 Tk Workshop Sl i de 60
Predefined button Bitmaps
proc buttonBitMap { Win } \
{
wm title . "Button Bitmaps";
pack [label .$Win -text "The button bitmaps: " \
-font {-size 14}] -side left;
#
foreach BitMap {warning error question questhead hourglass info}\
{button .bt$BitMap$Win -bitmap $BitMap -width 60 -height 40 \
-text "$BitMap" -compound top -default normal;
pack .bt$BitMap$Win -side left;
}
}
buttonBitMap x
2009-05-22 Tk Workshop Sl i de 61
A Custom button Image
proc buttonImage { Win } \
{wm title . "Tk Button with 'warning'";
image create bitmap tkIcon -file "xIcon.xbm"; # 64x64.
#
set BitMap warning;
button .bt$BitMap$Win -bitmap $BitMap -width 300 \
-height [expr 64 + 12 + 5] -text "$BitMap" \
-compound top -image tkIcon \
-bg white -fg blue -default normal;
pack .bt$BitMap$Win;
}
buttonImage x
2009-05-22 Tk Workshop Sl i de 62
Predefined tk_messageBox Bitmap
The name of the -bitmap opti on for thi s wi dget i s -icon!
proc msgBoxIcon { Win } \
{
# Suppress appearance of the inert main window:
wm withdraw .;
#
tk_messageBox -title "Message Box with Warning" \
-message {Here is a warning message to display} \
-parent . -icon warning -type ok;
}
msgBoxIcon x
exit
Noti ce the wi ndow banner i con! Thi s exampl e was run i n MS Wi ndows.
2009-05-22 Tk Workshop Sl i de 63
Lab 3: GUI Uti l i ty Di al ogs
Use the Tk hel p system for syntax:
tk_messageBox
tk_dialog
tk_chooseColor
tk_chooseDirectory
tk_getOpenFile
tk_getSaveFile
2009-05-22 Tk Workshop Sl i de 64
Putti ng Thi ngs Together
Mul ti pl e Wi ndows wi th toplevel
The labelframe Wi dget
The listbox Wi dget
The tk_popup Wi dget
2009-05-22 Tk Workshop Sl i de 65
Independent Windows for an Application
proc twoToplevelLabels { Win } \
{wm iconify .; # Suppress the unused root window.
#
set t1 [toplevel .t1$Win];
label $t1.a -font {-family Times -size 18} \
-text "This is the initial label";
wm title $t1 "First label";
#
set t2 [toplevel .t2$Win];
label $t2.a -font {-family Times -size 18} \
-text "This is another label";
wm title $t2 "Second label";
#
pack $t1.a $t2.a;
}
twoToplevelLabels x
2009-05-22 Tk Workshop Sl i de 66
labelframe Widget Example
proc labelFrameButtons { Win Img } \
{wm title . {Labelframe with Buttons};
variable ImgL $Img;
namespace eval iSpace {
variable Img [image create bitmap Img \
-file "$::ImgL" -back {light yellow} -fore {dark blue}];
}
proc ${Win}Run { Win Choice } \
{tk_dialog .lf$Win {Choice Done} "You chose $Choice" {} 0 {Dismiss};
exit;
}
labelframe .lf$Win -labelanchor n \
-text "Choose the base footprint for your new lamp:" \
-font {-size 14} -fg {dark green} -bg {light yellow};
label .lf$Win.img -image $iSpace::Img;
button .lf$Win.b1 -text {Circle} -command "${Win}Run $Win Circle" \
-font {-weight bold} -bg white -activefore red -activeback green;
button .lf$Win.b2 -text {Square} -command "${Win}Run $Win Square" \
-font {-weight bold} -bg white -activefore red -activeback green;
button .lf$Win.b3 -text {Hexagon} -command "${Win}Run $Win Hexagon" \
-font {-weight bold} -bg white -activefore red -activeback green;
pack .lf$Win .lf$Win.img;
pack .lf$Win.b1 .lf$Win.b2 .lf$Win.b3 -side left -expand 1;
}
labelFrameButtons x LabelFrameButtons.xbm;
2009-05-22 Tk Workshop Sl i de 67
labelframe Widget Result
Initial Display
Depression of
Button
Final Display
2009-05-22 Tk Workshop Sl i de 68
The listbox Widget
Basi cal l y a read-onl y text wi dget.
Each i tem termi nated by a scri pt NL.
One or more i tems sel ecti bl e.
Can't copy to cl i pboard (unl i ke text).
Automati c scrol l i ng, verti cal l y & hori zontal l y (l i ke text).
Speci al bind provi ded to vi rtual event, <<ListboxSelect>>
2009-05-22 Tk Workshop Sl i de 69
listbox Widget Options
Declaration Options
-font. The font used i n the listbox wi ndow.
-background; -foreground. Col ors i n the listbox wi ndow.
-height; -width. The hei ght i s i n l i nes; the wi dth i s i n characters.
-state. disabled or normal.
-listvariable. I f thi s opti on i s used, the listbox contents become
dynami cal l y l i nked to the vari abl e.
-selectmode. One i tem at a ti me (browse), or more than one
(extended).
Command Options:
curselection. Returns a l i st of i ndi ces of the sel ected listbox i tems.
insert. I nserts one or more new i tems i nto the listbox i tem l i st, at
i ndex.
get. Gi ven an i ndex i nto the listbox i tem l i st, thi s returns the i tem
stri ng.
2009-05-22 Tk Workshop Sl i de 70
Inert listbox Example
proc fileListBox { Win Dir } \
{wm title . {Listbox with Filenames};
set Flist [glob -nocomplain -tails -dir $Dir */*];
#
label .lDir$Win -text "$Dir" -wraplength {20 c} -bg grey90;
label .lFile$Win -text "$Flist" -wraplength { 8 c} -bg cornsilk;
listbox .lBox$Win -width 15 -height 6;
#
foreach f "$Flist" { .lBox$Win insert end $f; };
#
grid configure .lDir$Win -row 1 -columnspan 3;
grid configure .lFile$Win -row 2 -column 1;
grid configure .lBox$Win -row 2 -column 2;
}
fileListBox x d:/~;
2009-05-22 Tk Workshop Sl i de 71
Functional listbox Example (1st half)
proc fileChooseLB { W Dir } \
{wm title . {Listbox to Choose a Filename};
#
set Flist [glob -nocomplain -tails -dir $Dir */*];
#
frame .f$W -background {light goldenrod};
#
set HelpVar {Select any file in the list box on };
append HelpVar {the right. Your choice will be };
append HelpVar {confirmed; then the choice value };
append HelpVar {will be passed to an independent };
append HelpVar {window to simulate useful activity.};
#
label .f$W.lDir$W -text "$Dir" -wraplength {20 c} -bg grey90;
label .f$W.lMsg$W -text $HelpVar -wraplength { 8 c} -bg cornsilk;
listbox .f$W.lBox$W -width 15 -height 6;
#
foreach f "$Flist" { .f$W.lBox$W insert end $f; };
#
grid configure .f$W -row 1 -columnspan 3;
grid configure .f$W.lDir$W -row 1 -columnspan 3 -sticky {e w};
grid configure .f$W.lMsg$W -row 2 -column 1;
grid configure .f$W.lBox$W -row 2 -column 2;
# ...
2009-05-22 Tk Workshop Sl i de 72
Functional listbox Example (2nd half)
# ...
proc fileChooseLBsel { W } \
{ global TransferVar;
set Sel [.f$W.lBox$W curselection];
if {$Sel ne {} } \
{set Got [.f$W.lBox$W get $Sel];
set TransferVar $Got;
tk_dialog .f$W.d {Acknowledgement of Selection} \
"You chose $Got" {} 0 {Dismiss};
doIt;
}
}
#
bind .f$W.lBox$W <<ListboxSelect>> "fileChooseLBsel $W;";
}
proc doIt {} \
{ global TransferVar;
tk_messageBox -icon info -type ok -title "New Application Called" \
-message "Now processing $TransferVar";
};
fileChooseLB x D:/~/Lab01;
2009-05-22 Tk Workshop Sl i de 73
Functional listbox Result
Initial Display
Effect of Selection
Continuation after
Dismissal
2009-05-22 Tk Workshop Sl i de 74
tk_popup Command
tk_popup menu_path x_location y_location
• menu_path i s a wi ndow path to a menu wi dget wi ndow.
• x i s hori zontal offset i n pi xel s from l eft screen edge.
• y i s verti cal offset from top of screen.
2009-05-22 Tk Workshop Sl i de 75
menu Command
menu declaration options:
-tearoff. 1 creates a dotted tear-off l i ne near the top of the menu.
-disabledforeground. Foreground col or of a di sabl ed i tem.
menu execution option:
add command
Opti ons to the menu add command command:
-command. Gi ves the command to be binded to the menu i tem.
-label. Defi nes the text appeari ng on the menu i tem.
-background. Defi nes the background col or of an i tem (i f not di sabl ed).
-foreground. Defi nes the foreground col or of an i tem (i f not di sabl ed).
-state. Ei ther normal, active, or disabled.
2009-05-22 Tk Workshop Sl i de 76
menu Command Example
set m [menu .$Win -tearoff 0 -disabledforeground black];
$m add command -label {File...} -back green -state disabled;
$m add command -command "doList $Win" -label {List Dir...};
$m add command -command "doOpen $Win" -label {Open File...};
tk_popup .$Win 200 220;
A nontearoff menu wi th a ti tl e "File..." and two functi onal i tems.
• The top i tem i s l abel l ed "List Dir..." and, i f pi cked, runs doList().
• The second i tem i s l abel l ed "Open File..." and runs doOpen().
Thi s menu pops up whenever the tk_popup statement i s run.
The tk_popup statement woul d be binded to a GUI event.
2009-05-22 Tk Workshop Sl i de 77
Simple Popup GUI (Layout)
wm title . {My Clever Popup};
wm iconbitmap . @Tk.xbm;
wm geometry . =+150+150;
#
# Set up the Main Menu Bar widgets:
set L [label .labelWin -text "Make a choice: " -height 2 \
-font {-size 14 -weight bold} -bg blue -fg yellow];
set B1 [button .b1Win -text {Choice 1} -font {-size 14} \
-bd 6 -bg green -command {bell;}];
set B2 [button .b2Win -text {Choice 2} -font {-size 14} \
-bd 6 -bg green -command {bell;}];
set Bexit [button .bExitWin -text {Exit} -font {-size 14} \
-bd 6 -bg red -command {exit;}];
set Ans [label .ansWin -bg cornsilk];
# Runtime:
grid $L $B1 $B2 $Bexit -row 1;
grid $Ans -row 2 -columnspan 4 -sticky {e w};
2009-05-22 Tk Workshop Sl i de 78
Simple Popup GUI (Proto. Main Window)
wm title . {My Clever Popup};
wm iconbitmap . @Tk.xbm;
wm geometry . =+150+150;
#
# Set up the Main Menu Bar widgets:
set L [label .labelWin -text "Make a choice: " -height 2 \
-font {-size 14 -weight bold} -bg blue -fg yellow];
set B1 [button .b1Win -text {Access Files} -font {-size 14} \
-bd 6 -bg green -command {doPopFil ansWin;}];
set B2 [button .b2Win -text {Access Environment} -font \
{-size 14} -bd 6 -bg pink -command {doPopEnv ansWin;}];
set Bexit [button .bExitWin -text {Exit} -font {-size 14} \
-bd 6 -bg red -command {exit;}];
set Ans [label .ansWin -bg cornsilk]; # Placeholder (no grid).
#
# Runtime:
grid $L $B1 $B2 $Bexit -row 1;
2009-05-22 Tk Workshop Sl i de 79
Simple Popup GUI (Prototype menu procs)
proc doPopFil {Win} \
{if { [winfo exists .$Win] } { destroy .$Win; }
set m [menu .$Win -tearoff 0 -disabledforeground black];
$m add command -label {Filesystem Access} -back green -state disabled;
$m add command -command "doDirList $Win" -label {List Directory Contents...};
$m add command -command "doFileOpen $Win" -label {Open a File...};
tk_popup .$Win 200 220;
bind .$Win <1> "tk_popup .$Win 200 220";
}
proc doPopEnv {Win} \
{if { [winfo exists .$Win] } { destroy .$Win; }
set m [menu .$Win -tearoff 0 -disabledforeground black];
$m add command -label {Environment Access} -back pink -state disabled;
$m add command -command "doEnvList $Win" -label {List Selected Variables...};
$m add command -command "doEnvMod $Win" -label {Modify the Environment...};
tk_popup .$Win 200 220;
bind .$Win <1> "tk_popup .$Win 200 220";
}
[Access Files] button picked: [Access Environment] button picked:
2009-05-22 Tk Workshop Sl i de 80
Simple Popup GUI (Prototype item procs)
proc doDirList {x} \
{tk_messageBox -message "doDirList(): Not implemented";}
proc doFileOpen {x} \
{tk_messageBox -message "doFileOpen(): Not implemented";}
proc doEnvList {x} \
{tk_messageBox -message "doEnvList(): Not implemented";}
proc doEnvMod {x} \
{tk_messageBox -message "doEnvMod(): Not implemented";}
(Greyed-out l ower i tems to be dropped for si mpl i ci ty).
2009-05-22 Tk Workshop Sl i de 81
Simplification of Top Menu:
Remove the [Access Environment] choi ce:
From a Tk poi nt of vi ew, i t was al most the same as the remai ni ng one.
The resul ti ng menu (Wi ndows).
2009-05-22 Tk Workshop Sl i de 82
Simplification, with Real menu Item
proc doDirList { Win } \
{ ... (tk_chooseDirectory stuff omitted) ...
set DirGlob [glob -nocomplain -tails -dir $Choice *];
if { [llength $DirGlob] > 0 } \
{ set DirGlob [lsort $DirGlob];
foreach {f} "$DirGlob" { append DirList "$f\n"; }
} \
else { set DirList {(none found)}; }
# This permits repeated listings:
if { [winfo exists .$Win] } { destroy .$Win; };
text .$Win -height 10 -bg cornsilk;
.$Win insert end $DirList;
grid .$Win -row 2 -columnspan 2 -sticky {e w};
}
The Lab04 di rectory l i sti ng (Li nux).
2009-05-22 Tk Workshop Sl i de 83
Lab 4: I mage-Vi ewi ng GUI
Requi rements for thi s GUI :
2009-05-22 Tk Workshop Sl i de 84
Revi ew and Wrap-Up
2009-05-22 Tk Workshop Sl i de 85
What We Presented
⇒ The basi c el ements of a GUI : wi ndows, i mages, pal ettes, text, and wi dgets.
⇒ The rel ati onshi p of Tk to TcL and X.
⇒ A few general Tk commands, tk, wm, and winfo.
⇒ The three geometry managers, packer, gridder, and placer.
⇒ The essenti al s of fonts i n Tk.
⇒ The use of text and entry wi dgets.
⇒ Event bi ndi ng and text mani pul ati on.
⇒ The use of i mage namespaces.
⇒ The use and format of xbm i mages, thei r creati on and col ors.
⇒ tk_setPalette.
⇒ The most commonl y useful Tk wi dgets.
⇒ Creati on of mul ti pl e i ndependent wi ndows i n a si ngl e Tk scri pt.
⇒ The listbox.
⇒ The tk_popup and the menu wi dgets.
⇒ We fi ni shed wi th a l ab i mpl ementati on of a compl ete, si mpl e GUI appl i cati on.
2009-05-22 Tk Workshop Sl i de 86
What We Omitted
Di scussi on of the majori ty of the opti ons avai l abl e i n the wi dgets and other functi ons.
Di scussi on of many Tk commands, some of whi ch are qui te di fferent from those we have
covered:
• The fol l owi ng si mpl e wi dgets: checkbutton, message, menubutton,
panedwindow, radiobutton, scale, scrollbar, and spinbox.
• The fol l owi ng more compl ex functi ons:
(a) canvas for arbi trary graphi cal di spl ays associ ated wi th TcL commands;
(b) tkwait to acti vate concurrent procedures;
(c) bindtags and event;
(d) the clipboard, selection, and send commands for Tk GUI
i nterprocess communi cati on;
(e) al l drag and drop functi onal i ty.
• Coverage of cursor speci fi cati on and the grab command.
Di scussi on of the pl ethora of C and C++ i nterfaces defi ned by the Tk_* bui l ti n
procedures.
Numerous TcL packages, usual l y avai l abl e i n careful l y speci fi ed namespaces, whi ch
have been contri buted to TcL and Tk over the years.
2009-05-22 Tk Workshop Sl i de 87
That's I t.
(pl ease fi l l out eval uati on)

2009-05-22

Tk

Workshop

List of Slides
Introduction and Scope .............................................................................................................................................................................................0 Workshop Organization.......................................................................................................................................................................................1 Workshop Topics ..................................................................................................................................................................................................2 Anticipated Schedule ...........................................................................................................................................................................................3 TcL, Tk, and X ......................................................................................................................................................................................................4 Tk Naming Conventions......................................................................................................................................................................................5 Elementary GUI Objects ...........................................................................................................................................................................................6 Window .................................................................................................................................................................................................................7 Image ....................................................................................................................................................................................................................8 Image Creation Example.....................................................................................................................................................................................9 bitmap Image Format ........................................................................................................................................................................................10 Palette.................................................................................................................................................................................................................11 Text .....................................................................................................................................................................................................................12 Text Example .....................................................................................................................................................................................................13 Widget.................................................................................................................................................................................................................14 Windows: Systems and Controls ...........................................................................................................................................................................15 Tk Window Hierarchy........................................................................................................................................................................................16 Window Management I: tk Command .............................................................................................................................................................17 Window Management II: wm Command .........................................................................................................................................................18 wm iconbitmap Example ...................................................................................................................................................................................19 Window Management III: winfo Command ....................................................................................................................................................20 Geometry Management I: packer ....................................................................................................................................................................21 packer Example..................................................................................................................................................................................................22 Geometry Management II: gridder ..................................................................................................................................................................23 gridder Example.................................................................................................................................................................................................24 Geometry Management III: placer ..................................................................................................................................................................25 placer Example...................................................................................................................................................................................................26 Window Stacking: raise and lower...................................................................................................................................................................27 Window Stacking: raise Example ....................................................................................................................................................................28 The bitmap Image Tool......................................................................................................................................................................................29 The mtpaint Image Tool ....................................................................................................................................................................................30 Lab 1: label Widget and icon .................................................................................................................................................................................31 Text and Font Manipulation ..................................................................................................................................................................................32

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->