Лабораторная работа № 5
"Программирование GUI в Х-Window.
Язык программирования TCL/TK (тикл-так)"
1. Зарегистрироваться в системе, стартовать оконный интерфейс.
2. Определить наличие в файловой системе командной оболочки
TCL/TK - wish. Сохранить полный путь к wish первым в списке путей поиска.
3. Создать шаблон wish-скрипта для следующих пунктов лабораторного задания:
#!/usr/bin/wish -f
set tk_strictMotif 1
toplevel .vasja
.
.
.
4. Создать несколько widgets типа label с различными значениями ресурсов text, background, foreground, relief,
font. Расположить
их различными способами (опция -side команды pack).
5. Создать widget типа entry с видимой областью ввода и заданной шириной.
6. Создать набор widgets типа label и entry для контроля вводимых переменных. Пару расположить горизонтально, вертикально.
7. Создать widget типа scale для ввода целочисленной переменной, значение которой лежит в диапозоне 0-100, с шагом 10. Ориентировать widget горизонтально. Начальное значение слайдера - 40.
8. Создать widget типа button заданной ширины для запуска - при нажатии на нее - одного из известных вам Х-клиентов.
9. Используя widgets типа frame, scale,
button, (возможно -radiobutton, checkbutton), label, entry, разработать пользовательское Х-окно для работы с аудио-аппаратурой одной из известных фирм.
Пояснение:
На панели управления обязательно должны быть отображены регуляторы правого/левого канала записи, правого/левого каналов воспроизведения, кнопки выбора режимов запись/воспроизведение, индикатор состояния (запись/воспроизведение), кнопка включения, окно для ввода номера выбираемой для записи/прослушивания композиции.
Примеры генерации widgets с помощью конструкций языка TCL/TK
1.Label
widgets
label .label1 -text "This is a text label"
pack .label1_______________________________
label .Iabel2 -text "More text" -relief sunken
pack .Iabel2
label .Iabel3 -text "Coloured text"
-background red -foreground blue
pack .Iabel3_______________________________________
label .Iabel4 -text $text
pack .Iabel4
wish
set text "Hello there"
source label4.tcl
set
text "Bve for now"._______________________
label .Iabel4 -width 20 -textvariable text
#This example
shows different forms for the label widget
label .Iab1 -text "This is text"
label .Iab2 -text "This is coloured text"
-foreground red
-background
blue
label .Iab3 -text "Sunken text" -relief sunken
label .Iab4 -text "Grooved text" -relief groove
label .Iab5 -text "Flat text"
-relief flat
label .Iab6 -text "Ridged text" -relief ridge
label .Iab7 -text "Raised text" -relief raised
label .Iab8 -text "Times font"
-font
*-times-medium-r-normal~*-100-*
pack .Iab1 .Iab2 .Iab3 .Iab4 .Iab5 .Iab6 .Iab7 .Iab8 -padx
2m -pady 1m -fill x
2. Entry widgets
entry .entrybox1 -textvariable variable
pack
.entrybox1_______________________________
entry .entrybox2 -relief ridge -textvariable variable
_____________ pack .entrybox2______________________
entry .entrybox3 -width 30 -relief groove -textvariable
variable
pack .entrybox3
puts $variable
3. Listbox
widgets
listbox .listbox1
pack .listbox1
#The following is
an example of a widget specific command -this is
#the insert operation for listboxes, which inserts a list of
#items starting at line 0
.listboxi insert 0 red orange yellow green blue indigo violet
3. Scale widgets
#Make a scale, oriented vertically, going
down from 50 to 0.
#Tick marks are places alongside the scale
every 10 units.
scale .scale1 -width 10 -orient vertical -length 280
-from 50 -to
0 -command "set var1"
-tickinterval 10 -relief raised
label .Iab1 -width 10 -textvariable var1 -relief
sunken
pack .scale1 .Iab1 -padx 1m -pady
2m -fill x
#Now set the
value of scale to 25 using a widget command
.scale1 set 25
4. Command binding
#Set up a button
with a command"
button .button1 -text "Press Here" -command "exec echo Hello
there"
pack .button1________________________________________
#Set up a
button with a command"
button .button2 -text "Press
Here" -command "exec echo Hello $Name"
pack .button2
set Name "Groucho Marx"________________________________
#Set up a
button with a command"
button .button3 -text "Press Here" -command "exec echo Hello
$Name"
pack .button3
Set Name "Mickie
Mouse"
When the button is pressed, Groucho Marx is displayed.
5. Packing
For example
button .button1 -text "Buttoni" -command
"cmd1"
button .button2 -text "Button2" -command "cmd2"
button .button3 -text "Button3" -command "cmd3"
pack .button1 .button2 .button3
simply creates three buttons, and packs them vertically, while.
button .button1 -text "Buttoni" -command
"cmd1"
button .button2 -text "Button2" -command "cmd2"
button .button3 -text "Button3" -command "cmd3"
pack .buttoni .button2 .button3 -side left
packs the three buttons in a horizontal line.
6. Using frames to improve packing
Frames are widgets whose main
purpose is to contain other widgets - they don't do very much themselves. They
are useful for helping to pack widgets into two dimensional layouts. Suppose we
want to create the following layout:
label1
entry1
Iabel2
entry2
Iabel3
entry3
This can conveniently be done by
defining two frames to contain the two columns, and then packing the frames, as
shown below:
frame .f1
frame .f2
label .f1.label1 -text "Label1"
label .f1.label2 -text "Label2"
label .f1.Iabel3 -text "Label3"
#Vertically pack
labels
pack .f1.label1
.f1.label2 .f1.label3
entry .f2.entry1 -textvariable entrydata1 -relief
sunken
entry .f2.entry2 -textvariable entrydata2 -relief
sunken
entry .f2.entry3 -textvariable entrydata3 -relief
sunken
#Vertically pack
entry boxes
pack .f2.entry1 .f2.entry2 .f2.entry3
#horizontally pack columns
pack .f1 .f2 -side left
Alternatively, three frames packed vertically
above each other may be used to contain a single label and entry widget which
are packed side by side:
frame .f1
frame .f2
frame .f3
label .f1.label1 -text "Label 1"
entry .f1.entry1 -textvariable entrydata1 -relief
sunken
#pack these two horizontally
pack .f1.label1 .f1.entry1 -side left
label .f2.label1 -text "Label2"
entry .f2.entry1 -textvariable entrydata2 -relief
sunken
pack .f2.label1 .f2.entry1 -side left
label .f3.label1 -text "Label3"
entry .f3.entry1 -textvariable entrydata3 -relief
sunken
pack .f3.label1 .f3.entry1 -side left
#now pack each frame vertically
pack .f1 .f2 .f3
7. Using radio buttons
radiobutton .male -width 10 -text "Male" -variable sex -value
"Male"
radiobutton .female -width 10 -text "Female" -variable sex -value
"Female"
set sex Female
8. Using
check buttons
#set gender "Female" - initialisation - if needed
checkbutton .sex1 -width 15 -textvariable
"gender" -variable sex
-onvalue
Male -offvalue Female
-command {set gender $sex}
When the checkbutton
is set on, the value of the variable sex is set to Male, and when the button is
off, the value is set to Female.y
9. Menus
#First make a
menu button
menubutton .menu1 -text "Unix commands" -menu .menu1.m -underline 0
#Now make the
menu, and add the lines one at a time
menu .menu1.m
.menu1.m add command -label "List
Files" -command {Is}
.menu1.m add command -label "Get
date" -command {date}
.menu1.m add command -label "Start
calendar" -command {xcalendar}
pack .menu1
12. Data entry example
With the widgets so far described, it is
possible to make a small data entry example. It is not very sophisticated, and
carries out no data validation, but illustrates the ease of creating a data
entry screen.
The following personal data is to be
collected:
Surname, First names, Address, Telephone
number, Sex, Age
The layout of the display will have a
column of labels to the left, with a column of entry and other widgets to the
right. This
can be implemented using two frames, one for each column.
Additionally, when all the data is
entered, a Save button will store the data in a file, for future use, either by
a TCL program, or by an external program, and a Quit button will cause the
program to finish.
#Define 2 frames -1 to contain the
columns, and 1 to contain the
#Save and Quit button.
frame .fr1
frame .fr2
#Define two frames for the columns
frame .fr1.c1
frame .fr1.c2
#define labels
label .fr1.c1.Iab1 -text "Surname"
label .fr1.c1.lab2 -text "First Names"
label .fr1.c1.Iab3 -text "Address"
label .fr1.c1.lab4 -text "Telephone Number"
label .fr1.c1.lab5 -text "Sex"
label .fr1.c1.lab6 -text "Age"
#Now define the
other widgets for the data
entry .fr1.c2.surname1 -width 30 -relief
sunken -textvariable surname
entry .fr1.c2.firstname1 -width 30 -relief
sunken -textvariable firstnames
entry .fr1.c2.address1 -width 30
-relief sunken -textvariable address
entry .fr1.c2.telephone -width 20 -relief
sunken -textvariable telno
entry .fr1.c2.age1 -width 20 -relief
sunken -textvariable age
entry .fr1.c2.sex1 -width 20
-relief sunken -textvariable sex
#We shall defer
consideration of the use of radio buttons for
#the next section, so we will simply
allocate an entry widget for
#Sex for the moment.
#Now define the
buttons for saving and quitting
button .fr2.button1 -text "Save" -command {savecommand}
button .fr2.button2 -text "Quit" -command {exit}
#Note: the command for save could be done
by system
#dependent commands, or by TCL commands.
#For portability
it is best to package them into a TCL procedure
#Now pack all the
widgets together - first within each frame
#Column 1 widgets
pack .fr1.c1.lab1 .fr1.c1.lab2 .fr1.c1.lab3
.fr1.c1.lab4 .fr1.c1.lab5
.fr1.c1.lab6 -pady
1m
#Column 2 widgets
pack .fr1.c2.surname1 .fr1.c2.firstname1 .fr1.c2.address1 .fr1.c2.telephone
.fr1.c2.sex1 .fr1.c2.age1
-padx
3m -pady 1m -fill x
#Now pack frames
side by side
pack .fr1.c1 .fr1.c2 -side left
#now develop the procedure for saving the
data file
proc savecommand {} {
#external variables have to be declared as
"global"
global surname firstnames address telno sex age
set file [open /tmp/outfile w]
puts $file $surname
puts $file $firstnames
puts $file Saddress
puts $file $telno
puts $file $sex
puts $file Sage
close $file
}
#Note: In Unix
this could have been written as
#
proc savecommand {} {
#
global surname firstnames
address telno sex age
#
exec echo $surname > /tmp/outfile
#
exec echo $firstnames
>>
/tmp/outfile
#
exec echo $address >>
/tmp/outfile
#
exec echo $telno >> /tmp/outfile
#
exec echo $sex >>
/tmp/outfile
#
exec echo $age >> /tmp/outfile
#
}
# And finally
pack the Save and Quit buttons at the bottom
pack .fr2.button1 .fr2.button2 -padx 2m -pady 1m -fill x
pack .fr1
pack .fr2 -padx 2m -pady