Unit V TK
Unit V TK
• Tk refers to Toolkit and it provides cross platform GUI widgets, which helps
you in building a Graphical User Interface.
• Basic element of Tk is widget.
• Widget is a generic term for the part of a GUI that allows the user to interface
with the application and operating system.
• It was developed as an extension to Tcl scripting language by John Ousterhout.
• Visual interfaces are usually implemented using a library of functions that
implement a collection of building blocks: menus, dialog boxes, buttons etc.
• Tk originated as a toolkit using Tcl as the glue for such a collection of
functions.
• The functionality of Tk can also be accessed from Perl and Ruby ,
demonstrating that it is language-independent as well.
Features of Tk
•It is cross platform with support for Linux, Mac OS, Unix, and Microsoft
Windows operating systems.
•It is an open source.
•It provides high level of extendibility.
•It is customizable and configurable.
•It provides a large number of widgets.
•It can be used with other dynamic languages and not just Tcl.
•GUI looks identical across platforms.
Applications Built in Tk
Large successful applications have been built in Tcl/Tk.
•Dashboard Soft User Interface
•Forms GUI for Relational DB
•Ad Hoc GUI for Relational DB
•Software/Hardware System Design
•Xtask - Task Management
•Musicology with Tcl and Tk
•Calendar app
Tk - Environment
• Generally, all Mac and Linux mac come with Tk pre-installed.
The Tk Interpreter
• It is just a small program that enables you to type Tk commands and have them executed line
by line. It stops execution of a tcl file in case, it encounters an error unlike a compiler that
executes fully.
• Let's have a helloWorld.tcl file as follows.
• wish (Windowing Shell) is a simple scripting or interactive Unix shell for the X Window System
and Mac OS X.
• It provides users with the facility to be able to control graphical user interface components via
the Tk toolkit, and enables utilization of the Tcl programming language.
• wish is open source and is currently part of the Tcl/Tk programming suite.
Installation on Windows
•Download the latest version for windows installer from the list of
Active Tcl/Tk binaries available. Active Tcl/Tk community edition is free
for personal use.
•Run the downloaded executable to install the Tcl and Tk, which can be
done by following the on screen instructions.
•Now, we can build and run a Tcl file say helloWorld.tcl by switching to
folder containing the file using cd and then using the following step −
C:\Tcl> wish helloWorld.tcl
•Press enter and we will see an output as shown below −
Installation on Debian Based Systems
•In case, it's not available prebuilt in your OS, you can use the following
command to download and install Tcl-Tk −
$ sudo apt -get install tcl tk
•Now, we can build and run a Tcl file say helloWorld.tcl by switching to
folder containing the file using cd command and then using the
following steps −
$ wish helloWorld.tcl
•Press enter and we will see an output similar to the following −
Visual toolkits
• Low-level of visual interfaces is exceedingly tedious, basically because
every pixel on the screen has to be specified.
• The operating system provides a simple level of abstraction away from
pixels: for example, the X Window System(The X Window System is an
open source, cross platform, client-server computer software system
that provides a GUI in a distributed network environment) library Xlib
contains functions to
create an empty window
draw dots, lines rectangles, polygons and arcs
fill rectangles, polygons and arcs
draw text strings.
Consider the simple window shown in Figure 6.1, which has the usual
title bar, menu bar and scrollbars..To create this, the programmer must
write code for the following sequence of actions:
• The application has to include code to respond to
create the parent window external events created by the user
draw lines to create a border
draw rectangles for the title bar, menu bar and client
area
fill these with appropriate colours
draw text in the title bar
draw rectangles for the control buttons
draw patterns on the control buttons
draw text in the title bar and menu bar
draw rectangles for the scrollbars
draw rectangles for the scrolling buttons
draw patterns on the scrolling buttons to create the
arrows.
Fundamental concepts of Tk
• Tk uses Tcl to provide a command language to build graphical user interfaces
based on a collection of widgets .
• X Windows provides the basic framework for a GUI environment: drawing
and moving windows on the display device and interacting with a mouse and
keyboard.
• In X windows widgets were implemented in C using the X toolkit, and Tcl had
a dual role: it was used to implement a command language for creating and
positioning widgets, and as the language used to describe the effects of
external events like mouse clicks.
• An alternative view of Tk is that it defines a set of graphical objects (widgets)
and a collection of methods for manipulating those widgets
• Tk provides a set of Tcl commands that create and manipulate widgets.
• A widget is a window in a graphical user interface that has a particular
appearance and behavior.
• The terms widget and window are often used interchangeably.
• Widget types include buttons, scrollbars, menus, and text windows.
• Tk also has a general purpose drawing widget called a canvas that lets
you create lighter-weight items like lines, boxes and bitmaps.
Example 1
Or
Widget creation
•The name of a widget class is also the name of a command that will create
an instance of the class
e.g. button . b creates an instance of a button and assign the name . b to it.
•Note that widget names must start with a lower-case letter after the dot.
Widget properties
•Widgets have properties (or attributes) that determine their
appearance, e.g. their colour, the font to be used for text, etc.
•properties can be set when the widget is first created and can be
changed subsequently: when a widget is created command of the
same name is automatically defined for later use in configuring the
properties,
e.g.
button .b -text Go \
-command {.b configure -text Stop}
pack .b -padx 20 -pady 30
Widgets have a very large number of attributes - even a simple button
has 37 attributes but many widgets share a common set of attributes:
these include size, orientation, colour and appearance.
• There are so many common options available to all widgets and they
are listed below in the following table −
• Sr.No. Syntax & Description
1 -background color Used to set background color for widget.
2 -borderwidth width Used to draw with border in 3D effects.
3 -font fontDescriptor Used to set font for widget.
4 -foreground color Used to set foreground color for widget.
5 -height number Used to set height for widget.
6 -highlightbackground color Used to set the color rectangle
to draw around a widget when the widget does not have input focus.
7 -highlightcolor color Used to set the color rectangle to
draw around a widget when the widget has input focus.
8 -padx number Sets the padx for the widget.
9 -pady number Sets the pady for the widget.
10 -relief condition Sets the 3D relief for this widget. The condition
may be raised, sunken, flat, ridge, solid, or groove.
11 -text text Sets the text for the widget.
12 -textvariable varName Variable associated with the widget. When
the text of widget changes, the variable is set with text of widget.
13 -width number Sets the width for widget.
Geometry management
•Geometry managers arrange widgets on the screen.
•Widgets are invisible when first created: they become visible when
they are located on the screen to meet the requirements of the
interface designer by a geometry manager, which controls the
positioning of widgets.
•A geometry manager positions widgets within a frame, and complex
layouts can be achieved by placing frames within frames.
•Tk provides three geometry managers.
1. The pack geometry manager is constraint-based: the user specifies
constraints on the location of widgets e.g. stacking vertically or
horizontally,
•Pack was the only geometry manager in the original version of Tk.
2. The grid geometry manager allows widgets to be placed on a grid with
variable sized rows and columns.
•The user specifies the rows and columns to be occupied by a widget and
the geometry manager adjusts the size of the grid to fit.
3. The place geometry manager allows widgets to be positioned precisely
in term of absolute or relative x and y coordinates.
• Example
button .c -text okay
button .hello -text "Hello World";
grid .hello
grid .c
button .c -text okay
button .hello -text "Hello World";
grid .hello -row 5 -column 20
grid .c -row 10 -column 40
grid [label .myLabel -background red -text "Hello World" -relief ridge -
borderwidth 3] -padx 100 -pady 100
Tk by example
• The examples use the wish interactive shell, which is provided as part
of Tk: this provides a 'console' window in which the user types code,
and a second window which displays the results of executing the
code.
Example 1: A button
button .bl -text "Press Me" \
-command {.bl configure -text "You did!"}
pack .bl
• When this code is typed into the console window it generates an
interface with a button labelled 'Press Me'.
• When the button is 'pressed' by clicking the mouse on it, the display
changes, as shown in Figures
• In this case the area shrinks vertically to match the size of the button:
the horizontal size is constrained by the minimum size for the wish
shell's title bar
Using grid
• since we are only placing one widget we could use the grid geometry
manager. Replacing the line pack. bl by grid. bl would produce exactly
the same display, with the parent frame shrinking to fit the widget.
• The grid is elastic.
Entry widget
Entry widget allows user to create a box into which users can type an
editable line of text
#widgets.tcl
grid [label .myLabel -text "Label Widget" -textvariable labelText]
grid [text .myText -width 20 -height 5]
.myText insert 1.0 "Text\nWidget\n"
grid [entry .myEntry -text "Entry Widget"]
.myEntry insert 1 "This is entry box"
grid [message .myMessage -background red -foreground white -text "Message\
nWidget"]
grid [button .myButton1 -text "Button" -command "set labelText clicked"]
Output:
Example-2:
#Frame1.tcl
frame .myFrame1 -background red -relief ridge -borderwidth 8 -padx 10 -pady 10 -height \
100 -width 100
frame .myFrame2 -background blue -relief ridge -borderwidth 8 -padx 10 -pady 10 -height \
100 -width 50
pack .myFrame1
pack .myFrame2
Example 3:
#button3.tcl
grid [radiobutton .gender -text "Male" -variable gender -value "Male"] -row 1 -column 2
grid [radiobutton .gender1 -text "Female" -variable gender -value "Female"] -row 1 -column 3
grid [checkbutton .chk1 -text "Range 1" -variable occupied1]
grid [checkbutton .chk2 -text "Range 1" -variable occupied2]
• The list of the available widgets for drawing in canvas is listed below −
• Arc:
canvasName create arc x1 y1 x2 y2 options
x1 y1 and x2 y2 are the end points of an arc.
• Line:
canvasName create line x1 y1 x2 y2 ... xn yn options
x1 y1, x2 y2 ... xn yn are used to determine the end points of line segments.
• Rectangle:
canvasName create rectangle x1 y1 x2 y2 options
x1 y1 and x2 y2 are the end points of rectangle.
• Oval:
canvasName create oval x1 y1 x2 y2 options
x1 y1 and x2 y2 are the end points of oval.
• Polygon:
canvasName create polygon x1 y1 x2 y2 ... xn yn options
x1 y1 and x2 y2 ... xn yn are used to determine the end points of a polygon.
• Text
canvasName create text x y options
x and y are used to determine the position of text −
• Bitmap
canvasName create bitmap x y options
x and y set the location of bitmap −
• Example-4
• In a callback script %W is replaced by the name of the widget that raised the
event.
Perl -Tk
• Perl-Tk provides the functionality of Tk in the Perl environment, making it possible
to add a graphical user interface (GUI) to Perl scripts.
• The implementation approach is completely different from Tcl/Tk, which is a
command language written in Tel that allows us to create and manipulate a
collection of visual items called widgets.
• In contrast, Perl-Tk implements widgets as objects with a collection of methods to
manipulate them.
• Thus whereas in Tcl/Tk you associate an event with a callback using the bind
command with the widget name, the event and the callback script as arguments, in
Perl-Tk you invoke the widgets bind method with the event and the callback script
as arguments.
• Despite this fundamental difference, Perl-Tk is designed in such a way that a user
familiar with Tel/Tk can soon adapt
• For example, consider a trivial program that creates a button which
when pressed causes the program to terminate:
button .b1 -text "Press Me" \
-command {exit}
pack .b1
• The equivalent Perl-Tk program is as follows:
use Tk;
$mw :: new MainWindow;
$b1:: $mw->Button(-text=>"Press Me",
-command=>sub {exit})i
$b1 -> pack;
MainLoop;
• The first line invokes the Tk package.
• The second line creates a top-level main window, and the next line
invokes the window's button method to create an instance of a
button as a child of the main window.
• Next we call the button's pack method to invoke the pack geometry
manager, and finally we start the main event loop, which watches for
a mouse click on the button.
• Note the use of an anonymous subroutine composer in the -
command option.
• Perl-Tk script for the phonebook
use Tk;
sub by_name{
$Enumber = exists $phones{$Ename} ?
$phones{$Ename} : 'NOT FOUND’;
}
sub by_number {
my %by_number reverse %phones;
$Ename = exists $by_number{$Ephone} ?
$by_number{$Ephone} : "NOT FOUND";
}
open IN, 'd:\temp\phones.txt’;
@g <IN>;
close IN;
chomp @g:
%phones = split "\t", join "\t", @g;
$mw = new MainWindow;
$mw->Label(-text=>'Name: ‘)-> pack(-side=> 'top' , -pady=>2);
$name $mw->Entry(-width=>10, -relief=>'sunken', -textvariable=>\$Ename)->
pack(-pady=>2) ;
$mw->Label(-text=>'Phone: ')->pack(-pady=>2) ;
$phone = $mw->Entry(-width=>10, -relief=> 'sunken' f -textvariable=>\$Ephone)-
>pack (-pady=>2) ;
$mw->Button(-text=>'Exit',-command=>sub{exit})->pack(-pady=>2);
$name->bind( "<Return>", \&by_name) ;
$phone->bind( "<Return>" f \&by_number) ;
MainLooP;