zetcode ruby gtk tutorial
TRANSCRIPT
-
8/13/2019 ZetCode Ruby GTK Tutorial
1/65
ZetCode Ruby GTK tutorial
This is Ruby GTK tutorial. In this tutorial, you will learn the basics of GUI programming
with GTK in Ruby language. The tutorial is suitable for beginners and intermediate
programmers.
GTK
The GTK is a library for creating graphical user interfaces. The library is created in C
programming language. The GTK library is also called the GIM Tool!it. "riginally, the
library was created while de#eloping the GIM image manipulation program. $ince then, the
GTK became one of the most popular tool!its under %inu& and '$( Uni&. Today, most of
the GUI software in the open source world is created in )t or in GTK. %anguage bindings
e&ist for C**, ython, erl, +a#a, C, +a#a$cript, - and other programming languages.
Introduction to Ruby GTK
In this part of the Ruby GTK programming tutorial, we will introduce the GTK library and
create our first programs using the Ruby programming language.
The purpose of this tutorial is to get you started with the GTK and Ruby. Images for the
ibbles game can be downloaded here.
About
GTK is one of the leading tool!its for creating graphical user interfaces. Ruby is a popular
scripting language.
Simple example
In the first e&le, we create a simple window. The window is centered on the screen.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial
## This program centers a window on# the screen## author: jan bodnar# website: wwwetcodecom# last modi"ied: pril $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie
superset,title -Center-
/
http://zetcode.com/img/gui/rubygtk/images.ziphttp://zetcode.com/img/gui/rubygtk/images.zip -
8/13/2019 ZetCode Ruby GTK Tutorial
2/65
signal,connect -destroy- doGt)main,'uit
end
set,de"ault,sie $.% $%% set,window,position Gt)::+indow::012,C34T3R
show endend
Gt)init window 5 RubyppnewGt)main
This e&le shows a 012&022 p& window in the centre of the screen.
re'uire (gt)$(
The re'uire!eyword imports necessery types that we will use in the application.
class Rubypp * Gt)::+indow
The e&le inherits from a +indow. The 3indow is a tople#el container.
set,title -Center-
3e set a title for the window.
signal,connect -destroy- doGt)main,'uit
end
The destroye#ent is triggered, when we clic! on the close button in the titlebar. "r press 4lt
* 56. The method main,'uit7uits the application for good.
set,de"ault,sie $.% $%%
3e set a default si8e for the application window.
set,window,position Gt)::+indow::012,C34T3R
This line centers the window on the screen.
show
3hen e#erything is ready, we show the window on the screen.
Gt)init window 5 RubyppnewGt)main
These three lines set up the application.
0
-
8/13/2019 ZetCode Ruby GTK Tutorial
3/65
Creating a Tooltip
The second e&le will show a tooltip. 4 tooltip is a small rectangular window, which gi#es
a brief information about an ob9ect. It is usually a GUI component. It is part of the help
system of the application.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This code shows a tooltip on# a window and a button## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -Tooltips- signal,connect -destroy- do
Gt)main,'uitend
"i7ed 5 Gt)::8i7ednew
add "i7ed
button 5 Gt)::9uttonnew -9utton-
buttonset,sie,re'uest % ;.buttonset,tooltip,te7t -9utton widget-
"i7edput button .% .%
set,tooltip,te7t -+indow widget- set,de"ault,sie $.% $%% set,window,position Gt)::+indow::012,C34T3R
show,all
endend
Gt)init window 5 RubyppnewGt)main
The e&le creates a window. If we ho#er a mouse pointer o#er the area of the window, a
tooltip pops up.
buttonset,tooltip,te7t -9utton widget-
3e set a tooltip with the set,tooltip,te7t method.
:
-
8/13/2019 ZetCode Ruby GTK Tutorial
4/65
5igure; Tooltip
Quit button
In the last e&le of this section, we will create a 7uit button. 3hen we press this button,
the application terminates.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This program creates a 'uit# button +hen we press the button# the application terminates## author: jan bodnar
# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -
-
8/13/2019 ZetCode Ruby GTK Tutorial
5/65
Gt)main,'uitend
"i7edput button .% .%
set,de"ault,sie $.% $%%
set,window,position Gt)::+indow::012,C34T3R endend
Gt)init window 5 RubyppnewGt)main
3e use a 9uttonwidget. This is a #ery common widget. It shows a te&t label, image or both.
init,ui
3e delegate the creation of the user interface to the init,uimethod.
show,all
3e ha#e two options.
-
8/13/2019 ZetCode Ruby GTK Tutorial
6/65
5igure; )uit button
This section was an introduction to the GTK library with the Ruby language.
Layout management
In this chapter we will show how to lay out our widgets in windows or dialogs.
3hen we design the GUI of our application, we decide what widgets we will use and how we
will organi8e those widgets in the application. To organi8e our widgets, we use speciali8ed
non #isible widgets called layout containers. In this chapter, we will mention lignment,
8i7ed, =9o7and Table.
Fixed
The 8i7edcontainer places child widgets at fi&ed positions and with fi&ed si8es. This
container performs no automatic layout management. In most applications, we don>t use this
container. There are some speciali8ed areas, where we use it. 5or e&le games, speciali8ed
applications that wor! with diagrams, resi8able components that can be mo#ed ?li!e a chart in
a spreadsheet application@, small educational e&les.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial
## >n this program we lay out widgets# using absolute positioning## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
A
-
8/13/2019 ZetCode Ruby GTK Tutorial
7/65
set,title -8i7ed- signal,connect -destroy- do
Gt)main,'uitend
init,ui
set,de"ault,sie ;%% $% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
modi"y,bg Gt)::2TT3,41R?@ Gd)::ColornewAB%% B%% B%D
beginbardejoE 5 Gd)::0i7bu"new -bardejoEjpg-
rotunda 5 Gd)::0i7bu"new -rotundajpg- mincol 5 Gd)::0i7bu"new -mincoljpg- rescue >13rror 5F e puts e puts -cannot load images- e7it end
image 5 Gt)::>magenew bardejoE image$ 5 Gt)::>magenew rotunda image; 5 Gt)::>magenew mincol
"i7ed 5 Gt)::8i7ednew
"i7edput image $% $% "i7edput image$ % B% "i7edput image; H% .%
add "i7ed
endend
Gt)init window 5 RubyppnewGt)main
In our e&le, we show three small images on the window. 3e e&plicitely specify the &, y
coordinates, where we place these images.
modi"y,bg Gt)::2TT3,41R?@ Gd)::ColornewAB%% B%% B%D
5or better #isual e&perience, we change the bac!ground color to dar! gray.
bardejoE 5 Gd)::0i7bu"new -bardejoEjpg-
3e load the image from the dis! to the 0i7bu"ob9ect.
image 5 Gt)::>magenew bardejoEimage$ 5 Gt)::>magenew rotunda
B
-
8/13/2019 ZetCode Ruby GTK Tutorial
8/65
image; 5 Gt)::>magenew mincol
The >mageis a widget, that is used to display images. It ta!es 0i7bu"ob9ect in the
constructor.
"i7ed 5 Gt)::8i7ednew
3e create the 8i7edcontainer.
"i7edput image $% $%
3e place the first image at &=02, y=02 coordinates.
add "i7ed
5inally, we add the 8i7edcontainer to the 3indow.
5igure; 5i&ed
Buttons
The lignmentcontainer controls the alignment and the si8e of its child widget.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## >n this program we position two buttons# in the bottom right corner o" the window# +e use horiontal and Eertical bo7es## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
-
8/13/2019 ZetCode Ruby GTK Tutorial
9/65
class Rubypp * Gt)::+indow
de" initialie super
set,title -9uttons- signal,connect -destroy- do
Gt)main,'uitend
init,ui
set,de"ault,sie $B% .% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
Ebo7 5 Gt)::=9o7new "alse . hbo7 5 Gt)::I9o7new true ;
Ealign 5 Gt)::lignmentnew % % % Ebo7pac),start Ealign
o) 5 Gt)::9uttonnew -1K- o)set,sie,re'uest H% ;% close 5 Gt)::9uttonnew -Close-
hbo7add o) hbo7add close
halign 5 Gt)::lignmentnew % % % halignadd hbo7
Ebo7pac),start halign "alse "alse ;
add Ebo7 endend
Gt)init window 5 RubyppnewGt)main
In the code e&le, we place two buttons into the right bottom corner of the window. To
accomplish this, we use one hori8ontal bo& and one #ertical bo& and two alignment
containers.
Ealign 5 Gt)::lignmentnew % % %
This will put the child widget to the bottom.
Ebo7pac),start Ealign
-ere we place the lignmentwidget into the #ertical bo&.
D
-
8/13/2019 ZetCode Ruby GTK Tutorial
10/65
hbo7 5 Gt)::I9o7new true ;o) 5 Gt)::9uttonnew -1K-o)set,sie,re'uest H% ;%close 5 Gt)::9uttonnew -Close-
hbo7add o)hbo7add close
3e create a hori8ontal bo& and put two buttons inside it.
halign 5 Gt)::lignmentnew % % %halignadd hbo7
Ebo7pac),start halign "alse "alse ;
This will create an alignment container that will place its child widget to the right. 3e add
the hori8ontal bo& into the alignment container and pac! the alignment container into the
#ertical bo&. 3e must !eep in mind that the alignment container ta!es only one child widget.That>s why we must use bo&es.
5igure; 'uttons
Calculator skeleton
The Tablewidget arranges widgets in rows and columns.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial
## >n this program we create a s)eleton o"# a calculator +e use the Table widget## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
/2
-
8/13/2019 ZetCode Ruby GTK Tutorial
11/65
set,title -Calculator- signal,connect -destroy- do
Gt)main,'uitend
init,ui
set,de"ault,sie ;%% $.% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
Ebo7 5 Gt)::=9o7new "alse $
mb 5 Gt)::?enu9arnew "ilemenu 5 Gt)::?enunew
"ile 5 Gt)::?enu>temnew -8ile- "ileset,submenu "ilemenu mbappend "ile
Ebo7pac),start mb "alse "alse %
table 5 Gt)::Tablenew . true
tableattach Gt)::9uttonnewA-Cls-D % % tableattach Gt)::9uttonnewA-9c)-D $ % tableattach Gt)::@abelnew $ ; % tableattach Gt)::9uttonnewA-Close-D ; %
tableattach Gt)::9uttonnewA-H-D % $ tableattach Gt)::9uttonnewA--D $ $ tableattach Gt)::9uttonnewA-&-D $ ; $ tableattach Gt)::9uttonnewA-/-D ; $
tableattach Gt)::9uttonnewA--D % $ ; tableattach Gt)::9uttonnewA-.-D $ $ ; tableattach Gt)::9uttonnewA-B-D $ ; $ ; tableattach Gt)::9uttonnewA-J-D ; $ ;
tableattach Gt)::9uttonnewA--D % ; tableattach Gt)::9uttonnewA-$-D $ ; tableattach Gt)::9uttonnewA-;-D $ ; ; tableattach Gt)::9uttonnewA--D ; ;
tableattach Gt)::9uttonnewA-%-D % . tableattach Gt)::9uttonnewA--D $ . tableattach Gt)::9uttonnewA-5-D $ ; . tableattach Gt)::9uttonnewA-L-D ; .
Ebo7pac),start Gt)::3ntrynew "alse "alse %
Ebo7pac),end table true true %
add Ebo7
endend
//
-
8/13/2019 ZetCode Ruby GTK Tutorial
12/65
Gt)init window 5 RubyppnewGt)main
3e use the Tablewidget to create a calculator s!eleton.
table 5 Gt)::Tablenew . true
3e create a table widget with 1 rows and 6 columns. The third parameter is the homogenous
parameter. If set to true, all the widgets in the table are of same si8e. The si8e of all widgets is
e7ual to the largest widget in the table container.
tableattach Gt)::9uttonnewA-Cls-D % %
3e attach a button to the table container. To the topEleft cell of the table. The first two
parameters are the left and right sides of the cell, the last two parameters are the top and left
sides of the cell.
Ebo7pac),end table true true %
3e pac! the table widget into the #ertical bo&.
5igure; Calculator s!eleton
Windows
e&t we will create a more ad#anced e&le. 3e show a window, that can be found in the
+(e#eloper I(
-
8/13/2019 ZetCode Ruby GTK Tutorial
13/65
# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -+indows- signal,connect -destroy- do
Gt)main,'uitend
init,ui
set,de"ault,sie ;%% $.%
set,window,position Gt)::+indow::012,C34T3Rshow,all
end
de" init,ui
set,border,width .
table 5 Gt)::Tablenew "alse tableset,column,spacings ;
title 5 Gt)::@abelnew -+indows-
halign 5 Gt)::lignmentnew % % % % halignadd title
tableattachAhalign % % Gt)::8>@@ Gt)::8>@@ % %D
"rame 5 Gt)::8ramenew tableattachA"rame % $ ; Gt)::8>@@ M Gt)::3N04O Gt)::8>@@ M Gt)::3N04O D
actiEate 5 Gt)::9uttonnew -ctiEate- actiEateset,sie,re'uest .% ;% tableattachAactiEate ; $ Gt)::8>@@ Gt)::2IR>4K D
Ealign 5 Gt)::lignmentnew % % % % close 5 Gt)::9uttonnew -Close- closeset,sie,re'uest H% ;% Ealignadd close tableset,row,spacing ; tableattachAEalign ; $ ; Gt)::8>@@ Gt)::8>@@ M Gt)::3N04O D
halign$ 5 Gt)::lignmentnew % % % help 5 Gt)::9uttonnew -Ielp- helpset,sie,re'uest H% ;% halign$add help tableset,row,spacing ; B
/:
-
8/13/2019 ZetCode Ruby GTK Tutorial
14/65
tableattachAhalign$ % . Gt)::8>@@ Gt)::8>@@ % %D
o) 5 Gt)::9uttonnew -1K- o)set,sie,re'uest H% ;% tableattachAo) ; . Gt)::8>@@
Gt)::8>@@ % %Dadd table
endend
Gt)init window 5 RubyppnewGt)main
The code e&le shows, how we can create a similar window in Ruby GTK.
table 5 Gt)::Tablenew "alsetableset,column,spacings ;
The e&le is based on the Tablecontainer. There will be :p& space between columns.
title 5 Gt)::@abelnew -+indows-
halign 5 Gt)::lignmentnew % % % %halignadd title
tableattachAhalign % % Gt)::8>@@ Gt)::8>@@ % %D
This code creates a label, that is aligned to the left. The label is placed in the first row of theTable container.
"rame 5 Gt)::8ramenewtableattachA"rame % $ ; Gt)::8>@@ M Gt)::3N04O Gt)::8>@@ M Gt)::3N04O D
The frame #iew widget spans two rows and two columns.
Ealign 5 Gt)::lignmentnew % % % %close 5 Gt)::9uttonnew -Close-closeset,sie,re'uest H% ;%Ealignadd closetableset,row,spacing ;tableattachAEalign ; $ ; Gt)::8>@@ Gt)::8>@@ M Gt)::3N04O D
3e put the close button ne&t to the frame widget into the fourth column. ?we count from
8ero@ 3e add the button into the alignment widget, so that we can align it to the top.
/6
-
8/13/2019 ZetCode Ruby GTK Tutorial
15/65
5igure; 3indows
In this part of the Ruby GTK tutorial, we mentioned layout management of widgets.
Widgets
In this part of the Ruby GTK programming tutorial, we will introduce some widgets.
3idgets are basic building bloc!s of a GUI application. "#er the years, se#eral widgets
became a standard in all tool!its on all "$ platforms. 5or e&le a button, a chec! bo& or a
scroll bar. The GTK tool!it>s philosophy is to !eep the number of widgets at a minimumle#el. More speciali8ed widgets are created as custom GTK widgets.
CheckButton
Chec)9uttonis a widget, that has two states. "n and "ff. The "n state is #isualised by a
chec! mar!. It is used to denote some boolean property.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This program toggles the title o" the# window with the Chec)9utton widget## author: jan bodnar# website: wwwetcodecom# last modi"ied: pril $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow de" initialie super
set,title -Chec)9utton- signal,connect -destroy- do
/1
-
8/13/2019 ZetCode Ruby GTK Tutorial
16/65
Gt)main,'uitend
init,ui
set,de"ault,sie $.% $%%
set,window,position Gt)::+indow::012,C34T3R show,all end
de" init,ui
"i7ed 5 Gt)::8i7ednew add "i7ed
cb 5 Gt)::Chec)9uttonnew -2how title- cbset,actiEe true cbset,can,"ocus "alse
cbsignal,connectA-clic)ed-D do MwM on,clic)edAwD end
"i7edput cb .% .%
end
de" on,clic)ed sender
i" senderactiEeP sel"set,title -Chec) 9utton- else
sel"set,title -- end endend
Gt)init window 5 RubyppnewGt)main
3e will display a title in the titlebar of the window, depending on the state of the
Chec)9utton.
cb 5 Gt)::Chec)9uttonnew -2how title-
Chec)9uttonwidget is created.
cbset,actiEe true
The title is #isible by default, so we chec! the chec! button by default.
i" senderactiEeP sel"set,title -Chec) 9utton-else sel"set,title --
end
/A
-
8/13/2019 ZetCode Ruby GTK Tutorial
17/65
3e show the title, if the button is chec!ed.
5igure; Chec!'utton
abel
The @abelwidget shows te&t.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This e7ample demonstrates the @abel widget## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
Qlyrics 5 S?eet you downstairs in the bar and heardyour rolled up sleeEes and your s)ull tshirtou say why did you do it with him todayPand sni"" me out li)e > was Tan'ueray
cause you(re my "ella my guyhand me your stella and "lyby the time >(m out the dooryou tear men down li)e Roger ?oore
> cheated mysel"li)e > )new > would> told ya > was troubleyou )now that >(m no goodU
class Rubypp * Gt)::+indow
de" initialie super
set,title -ou )now >(m no Good- signal,connect -destroy- do
Gt)main,'uit
/B
-
8/13/2019 ZetCode Ruby GTK Tutorial
18/65
end
init,ui
set,de"ault,sie $.% $%% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
set,border,width % label 5 Gt)::@abelnew Qlyrics add label
endend
Gt)init window 5 RubyppnewGt)main
The code e&le shows some lyrics on the window.
Qlyrics 5 S?eet you downstairs in the bar and heardyour rolled up sleeEes and your s)ull tshirt
3e create a multi line te&t.
set,border,width %
The @abelis surrounded by some empty space.
label 5 Gt)::@abelnew Qlyricsadd label
The @abelwidget is created and added to the window.
/
-
8/13/2019 ZetCode Ruby GTK Tutorial
19/65
5igure; %abel 3idget
!ntr"
The 3ntryis a single line te&t entry field. This widget is used to enter te&tual data.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This e7ample demonstrates the 3ntry widget## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -3ntry- signal,connect -destroy- do
Gt)main,'uitend
init,ui
set,de"ault,sie $.% $%% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
"i7ed 5 Gt)::8i7ednew
label 5 Gt)::@abelnew -- "i7edput label B% %
entry 5 Gt)::3ntrynew "i7edput entry B% %%
entrysignal,connect -)eyreleaseeEent- do Mw eM on,)ey,releaseAw e labelD end
addA"i7edD end
de" on,)ey,release sender eEent label labelset,te7t senderte7t end
end
Gt)init
/D
-
8/13/2019 ZetCode Ruby GTK Tutorial
20/65
window 5 RubyppnewGt)main
This e&le shows an entry widget and a label. The te&t that we !ey in the entry is
displayed immediately in the label widget.
entry 5 Gt)::3ntrynew
3ntrywidget is created.
entrysignal,connect -)eyreleaseeEent- do Mw eM on,)ey,releaseAw e labelDend
3e plug the on,)ey,releasemethod to the )eyreleaseeEentof the 3ntrywidget.
de" on,)ey,release sender eEent label
labelset,te7t senderte7tend
3e get the te&t from the 3ntrywidget and set it to the label.
5igure; magewidget shows an image.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This e7ample demonstrates the >mage widget## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
02
-
8/13/2019 ZetCode Ruby GTK Tutorial
21/65
class Rubypp * Gt)::+indow
de" initialie super
set,title -Red Roc)-
signal,connect -destroy- doGt)main,'uitend
init,ui
set,de"ault,sie $.% $%% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
set,border,width $
begin image 5 Gt)::>magenew -redroc)png- rescue puts -cannot load image- e7it end
add image end
end
Gt)init window 5 RubyppnewGt)main
In our e&le, we show an image on the window.
set,border,width $
3e put some empty border around the image.
begin image 5 Gt)::>magenew -redroc)png-rescue puts -cannot load image- e7itend
The >magewidget is created. I" operations are error prone, so we handle the possible
e&ceptions.
add image
3idget is added to the container.
0/
-
8/13/2019 ZetCode Ruby GTK Tutorial
22/65
5igure; Image widget
ComboBox
Combo9o7is a widget that allows the user to choose from a list of options.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This e7ample demonstrates the Combo9o7 widget#
# author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -Combo9o7-
signal,connect -destroy- doGt)main,'uitend
init,ui
set,de"ault,sie $.% $%% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
"i7ed 5 Gt)::8i7ednew label 5 Gt)::@abelnew ((
00
-
8/13/2019 ZetCode Ruby GTK Tutorial
23/65
"i7edput label .% %
cb 5 Gt)::Combo9o7new cbsignal,connect -changed- do Mw eM on,changedAw e labelD end
cbappend,te7t (Vbuntu( cbappend,te7t (?andriEa( cbappend,te7t (Redhat( cbappend,te7t (Gento( cbappend,te7t (?int(
"i7edput cb .% ;%
add "i7ed
end
de" on,changed sender eEent label labelset,label senderactiEe,te7t endend
Gt)init window 5 RubyppnewGt)main
The e&le shows a combo bo& and a label. The combo bo& has a list of fi#e options. These
are the names of %inu& (istros. The label widget shows the selected option from the combo
bo&.
cb 5 Gt)::Combo9o7new
The Combo9o7widget is created.
cbappend,te7t (Vbuntu(cbappend,te7t (?andriEa(cbappend,te7t (Redhat(cbappend,te7t (Gento(cbappend,te7t (?int(
It is filled with data.
de" on,changed sender eEent label labelset,label senderactiEe,te7tend
Inside the on,changedmethod, we get the selected te&t out of the combo bo& and set it to the
label.
0:
-
8/13/2019 ZetCode Ruby GTK Tutorial
24/65
5igure; Combo'o&
In this chapter of the Ruby GTK tutorial, we showed some basic widgets.
Menus & toolbars
In this part of the Ruby GTK programming tutorial, we will wor! with menus F toolbars.
4 menubaris one of the most common parts of the GUI application. It is a group of
commands located in #arious menus. 3hile in console applications you ha#e to remember all
those arcane commands, here we ha#e most of the commands grouped into logical parts.
These are accepted standards that further reduce the amount of time spending to learn a new
application.
Simple menu
In our first e&le, we will create a menubar with one file menu. The menu will ha#e only
one menu item. 'y selecting the item the application 7uits.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This e7ample shows a simple menu#
# author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -2imple menu-
signal,connect -destroy- doGt)main,'uit
06
-
8/13/2019 ZetCode Ruby GTK Tutorial
25/65
end
init,ui
set,de"ault,sie $.% $%% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
modi"y,bg Gt)::2TT3,41R?@ Gd)::ColornewAB%% B%% B%D
mb 5 Gt)::?enu9arnew
"ilemenu 5 Gt)::?enunew "ilem 5 Gt)::?enu>temnew -8ile- "ilemset,submenu "ilemenu
e7it 5 Gt)::?enu>temnew -37it- e7itsignal,connect -actiEate- do Gt)main,'uit end
"ilemenuappend e7it
mbappend "ilem
Ebo7 5 Gt)::=9o7new "alse $ Ebo7pac),start mb "alse "alse %
add Ebo7 endend
Gt)init window 5 RubyppnewGt)main
This is a small e&le with minimal menubar functionality.
mb 5 Gt)::?enu9arnew
?enu9arwidget is created. This is a container for the menus.
"ilemenu 5 Gt)::?enunew"ilem 5 Gt)::?enu>temnew -8ile-"ilemset,submenu "ilemenu
Tople#el ?enu>temis created.
e7it 5 Gt)::?enu>temnew -37it-e7itsignal,connect -actiEate- do Gt)main,'uitend
"ilemenuappend e7it
01
-
8/13/2019 ZetCode Ruby GTK Tutorial
26/65
temis created and appended to the 5ile ?enu>tem.
mbappend "ilem
Tople#el ?enu>temis appended to the ?enu9arwidget.
Ebo7 5 Gt)::=9o7new "alse $Ebo7pac),start mb "alse "alse %
Unli!e in other tool!its, we ha#e to ta!e care of the layout management of the menubar
oursel#es. 3e put the menubar into the #ertical bo&.
5igure; $imple menu
Submenu
"ur final e&le demonstrates how to create a submenu.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This e7ample shows a submenu## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -2ubmenu- signal,connect -destroy- do
Gt)main,'uitend
init,ui
0A
-
8/13/2019 ZetCode Ruby GTK Tutorial
27/65
set,de"ault,sie $.% $%% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
modi"y,bg Gt)::2TT3,41R?@ Gd)::ColornewAB%% B%% B%D
mb 5 Gt)::?enu9arnew
"ilemenu 5 Gt)::?enunew "ilem 5 Gt)::?enu>temnew -8ile- "ilemset,submenu "ilemenu
mbappend "ilem
imenu 5 Gt)::?enunew
importm 5 Gt)::?enu>temnew ->mport- importmset,submenu imenu
inews 5 Gt)::?enu>temnew ->mport news "eed- iboo)mar)s 5 Gt)::?enu>temnew ->mport boo)mar)s- imail 5 Gt)::?enu>temnew ->mport mail-
imenuappend inews imenuappend iboo)mar)s imenuappend imail
"ilemenuappend importme7it 5 Gt)::?enu>temnew -37it-
e7itsignal,connect -actiEate- do Gt)main,'uit end
"ilemenuappend e7it
Ebo7 5 Gt)::=9o7new "alse $ Ebo7pac),start mb "alse "alse %
add Ebo7 endend
Gt)init window 5 RubyppnewGt)main
$ubmenu creation.
imenu 5 Gt)::?enunew
4 submenu is a ?enu.
importm 5 Gt)::?enu>temnew ->mport-importmset,submenu imenu
0B
-
8/13/2019 ZetCode Ruby GTK Tutorial
28/65
It is a submenu of a menu item, which belogs to tople#el file menu.
inews 5 Gt)::?enu>temnew ->mport news "eed-iboo)mar)s 5 Gt)::?enu>temnew ->mport boo)mar)s-imail 5 Gt)::?enu>temnew ->mport mail-
imenuappend inewsimenuappend iboo)mar)simenuappend imail
$ubmenu has its own menu items.
5igure; $ubmenu
#mage menu
In the ne&t e&le, we will further e&plore the menus. 3e will add images and accelerators
to our menu items. Acceleratorsare !eyboard shortcuts for acti#ating a menu item.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This e7ample shows a menu with# images accelerators and a separator## author: jan bodnar# website: wwwetcodecom
# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title ->mage menu- signal,connect -destroy- do
Gt)main,'uit
end
0
-
8/13/2019 ZetCode Ruby GTK Tutorial
29/65
init,ui
set,de"ault,sie $.% $%% set,window,position Gt)::+indow::012,C34T3R
show,all
endde" init,ui
modi"y,bg Gt)::2TT3,41R?@ Gd)::ColornewAB%% B%% B%D
mb 5 Gt)::?enu9arnew
"ilemenu 5 Gt)::?enunew "ilem 5 Gt)::?enu>temnew -8ile- "ilemset,submenu "ilemenu
agr 5 Gt)::ccelGroupnew
add,accel,group agr
newi 5 Gt)::>mage?enu>temnew Gt)::2toc)::43+ agr )ey mod 5 Gt)::cceleratorparse -4- newiadd,acceleratorA-actiEate- agr )ey
mod Gt)::CC3@,=>2>9@3D "ilemenuappend newi
openm 5 Gt)::>mage?enu>temnew Gt)::2toc)::1034 agr )ey mod 5 Gt)::cceleratorparse -1- openmadd,acceleratorA-actiEate- agr )ey
mod Gt)::CC3@,=>2>9@3D "ilemenuappend openm
sep 5 Gt)::2eparator?enu>temnew "ilemenuappend sep
e7it 5 Gt)::>mage?enu>temnew Gt)::2toc)::T agr )ey mod 5 Gt)::cceleratorparse -2>9@3D
e7itsignal,connect -actiEate- do Gt)main,'uit end "ilemenuappend e7it
mbappend "ilem
Ebo7 5 Gt)::=9o7new "alse $ Ebo7pac),start mb "alse "alse %
add Ebo7 endend
Gt)init window 5 RubyppnewGt)main
0D
-
8/13/2019 ZetCode Ruby GTK Tutorial
30/65
"ur e&le shows a tople#el menu item with three suble#el menu items. mage?enu>temnew Gt)::2toc)::43+ agr)ey mod 5 Gt)::cceleratorparse -4-newiadd,acceleratorA-actiEate- agr )ey
mod Gt)::CC3@,=>2>9@3D"ilemenuappend newi
>mage?enu>temis created. The image comes from the stoc! of images. 3e create also a
Ctrl* accelerator.
sep 5 Gt)::2eparator?enu>temnew"ilemenuappend sep
These lines create a separator. It is used to put menu items into logical groups.
5igure; Image menu
Menus group commands that we can use in application. Toolbars pro#ide a 7uic! access to
the most fre7uently used commands.
Simple toolbar
e&t we create a simple toolbar.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This e7ample shows a toolbar# widget#
# author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
:2
-
8/13/2019 ZetCode Ruby GTK Tutorial
31/65
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -Toolbar- signal,connect -destroy- do
Gt)main,'uitend
init,ui
set,de"ault,sie $.% $%% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
toolbar 5 Gt)::Toolbarnew toolbarset,toolbar,style Gt)::Toolbar::2tyle::>C142
newtb 5 Gt)::Tool9uttonnew Gt)::2toc)::43+ opentb 5 Gt)::Tool9uttonnew Gt)::2toc)::1034 saEetb 5 Gt)::Tool9uttonnew Gt)::2toc)::2=3 sep 5 Gt)::2eparatorTool>temnew 'uittb 5 Gt)::Tool9uttonnew Gt)::2toc)::T
toolbarinsert % newtb toolbarinsert opentb toolbarinsert $ saEetb toolbarinsert ; sep toolbarinsert 'uittb
'uittbsignal,connect -clic)ed- do Gt)main,'uit end
Ebo7 5 Gt)::=9o7new "alse $ Ebo7pac),start toolbar "alse "alse %
addAEbo7D endend
Gt)init window 5 RubyppnewGt)main
The e&le shows a toolbar and four tool buttons.
toolbar 5 Gt)::Toolbarnew
4 Toolbarwidget is created.
:/
-
8/13/2019 ZetCode Ruby GTK Tutorial
32/65
toolbarset,toolbar,style Gt)::Toolbar::2tyle::>C142
"n toolbar, we show only icons. o te&t.
newtb 5 Gt)::Tool9uttonnew Gt)::2toc)::43+
4 Tool9uttonwith an image from stoc! is created. The image comes from the builtEin stoc!
of images.
sep 5 Gt)::2eparatorTool>temnew
This is a separator. It can be used to put toolbar buttons into logical groups.
toolbarinsert % newtbtoolbarinsert opentb
Toolbar buttons are inserted into the toolbar widget.
5igure; Toolbar
$ndo redo
The following e&le demonstrates, how we can deacti#ate toolbar buttons on the toolbar.
It is a common practise in GUI programming. 5or e&le the sa#e button. If we sa#e all
changes of our document to the dis!, the sa#e button is deacti#ated in most te&t editors. This
way the application indicates to the user, that all changes are already sa#ed.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This e7ample shows how to# actiEate/deactiEate a Tool9utton## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
:0
-
8/13/2019 ZetCode Ruby GTK Tutorial
33/65
class Rubypp * Gt)::+indow
de" initialie
super
set,title -Vndo redo- signal,connect -destroy- do
Gt)main,'uitend
Wcount 5 $
init,ui
set,de"ault,sie $.% $%% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
toolbar 5 Gt)::Toolbarnew toolbarset,toolbar,style Gt)::Toolbar::2tyle::>C142
Wundo 5 Gt)::Tool9uttonnew Gt)::2toc)::V4O1 Wredo 5 Gt)::Tool9uttonnew Gt)::2toc)::R3O1 sep 5 Gt)::2eparatorTool>temnew 'uit 5 Gt)::Tool9uttonnew Gt)::2toc)::T
toolbarinsert % Wundo toolbarinsert Wredo toolbarinsert $ sep toolbarinsert ; 'uit
Wundosignal,connect -clic)ed- do on,undo end
Wredosignal,connect -clic)ed- do on,redo end
'uitsignal,connect -clic)ed- do Gt)main,'uit end
Ebo7 5 Gt)::=9o7new "alse $ Ebo7pac),start toolbar "alse "alse %
sel"add Ebo7
end
de" on,undo
Wcount 5 Wcount
i" Wcount *5 %
::
-
8/13/2019 ZetCode Ruby GTK Tutorial
34/65
Wundoset,sensitiEe "alse Wredoset,sensitiEe true end end
de" on,redo Wcount 5 Wcount L
i" Wcount F5 . Wredoset,sensitiEe "alse Wundoset,sensitiEe true end endend
Gt)init window 5 RubyppnewGt)main
"ur e&le creates undo and redo buttons from the GTK stoc! resources. 4fter se#eral
clic!s each of the buttons is deacti#ated. The buttons are grayed out.
Wcount 5 $
The Wcount#ariable decides, which button is acti#ated or deacti#ated.
Wundo 5 Gt)::Tool9uttonnew Gt)::2toc)::V4O1Wredo 5 Gt)::Tool9uttonnew Gt)::2toc)::R3O1
3e ha#e two tool buttons. Undo and redo tool buttons. Images come from the stoc!resources.
Wundosignal,connect -clic)ed- do on,undoend
Clic!ing on the undo button, we trigger the on,undomethod.
i" Wcount *5 % Wundoset,sensitiEe "alse Wredoset,sensitiEe true
end
To acti#ate or deacti#ate a widget, we use the set,sensitiEemethod
:6
-
8/13/2019 ZetCode Ruby GTK Tutorial
35/65
5igure; Undo redo
In this chapter of the Ruby GTK tutorial, we showed, how to wor! with menus F toolbars.
Dialogs
In this part of the Ruby GTK programming tutorial, we will introduce dialogs.
(ialog windows or dialogs are an indispensable part of most modern GUI applications. 4
dialog is defined as a con#ersation between two or more persons. In a computer application a
dialog is a window which is used to tal! to the application. 4 dialog is used to input data,
modify data, change the application settings etc. (ialogs are important means of
communication between a user and a computer program.
%essage boxes
Message dialogs are con#enient dialogs that pro#ide messages to the user of the application.
The message consists of te&tual and image data.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This e7ample shows message# dialogs
## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -?essages- signal,connect -destroy- do
:1
-
8/13/2019 ZetCode Ruby GTK Tutorial
36/65
Gt)main,'uitend
init,ui
set,de"ault,sie $.% %%
set,window,position Gt)::+indow::012,C34T3Rshow,all
end
de" init,ui
table 5 Gt)::Tablenew $ $ true
in"o 5 Gt)::9uttonnew ->n"ormation- warn 5 Gt)::9uttonnew -+arning- 'ues 5 Gt)::9uttonnew -TI,0R34T Gt)::?essageOialog::>481
Gt)::?essageOialog::9VTT142,C@123 -Oownload completed-D mdrun mddestroy end
de" on,erro md 5 Gt)::?essageOialognewAsel" Gt)::Oialog::?1O@ M Gt)::Oialog::O32TR1,+>TI,0R34T Gt)::?essageOialog::3RR1R
Gt)::?essageOialog::9VTT142,C@123 -3rror loading "ile-D mdrun mddestroy end
:A
-
8/13/2019 ZetCode Ruby GTK Tutorial
37/65
de" on,'ues md 5 Gt)::?essageOialognewAsel" Gt)::Oialog::O32TR1,+>TI,0R34T Gt)::?essageOialog::14
Gt)::?essageOialog::9VTT142,C@123 -re you sure to 'uitP-D
mdrun mddestroy end
de" on,warn md 5 Gt)::?essageOialognewAsel" Gt)::Oialog::O32TR1,+>TI,0R34T Gt)::?essageOialog::+R4>4G
Gt)::?essageOialog::9VTT142,C@123 -Vnallowed operation-D mdrun mddestroy endend
Gt)init window 5 RubyppnewGt)main
In our e&le, we will show four !inds of message dialogs. Information, 3arning, )uestion
and
-
8/13/2019 ZetCode Ruby GTK Tutorial
38/65
About&ialog
The boutOialogdisplays information about the application. boutOialogcan display a
logo, the name of the application, #ersion, copyright, website or licence information. It is also
possible to gi#e credits to the authors, documenters, translators and artists.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This e7ample demonstrates the# boutOialog dialog## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -bout dialog- signal,connect -destroy- do
Gt)main,'uitend
init,ui
set,de"ault,sie ;%% .% set,window,position Gt)::+indow::012,C34T3R
show,all end
:
-
8/13/2019 ZetCode Ruby GTK Tutorial
39/65
de" init,ui
button 5 Gt)::9uttonnew -bout-
buttonset,sie,re'uest % ;%
buttonsignal,connect -clic)ed- do on,clic)ed end
"i7 5 Gt)::8i7ednew "i7put button $% $%
add "i7
end
de" on,clic)ed about 5 Gt)::boutOialognew
aboutset,program,name -9attery- aboutset,Eersion -%- aboutset,copyright -AcD 6an 9odnar- aboutset,comments -9attery is a simple tool "or battery chec)ing- aboutset,website -http://wwwetcodecom- aboutset,logo Gd)::0i7bu"new -batterypng- aboutrun aboutdestroy endend
Gt)init window 5 Rubyppnew
Gt)main
The code e&le uses a boutOialogwith some of its features.
about 5 Gt)::boutOialognew
3e create an boutOialog.
aboutset,program,name -9attery-aboutset,Eersion -%-aboutset,copyright -AcD 6an 9odnar-
-ere we specify the name, the #ersion and the copyright.
aboutset,logo Gd)::0i7bu"new -batterypng-
This line creates a logo.
:D
-
8/13/2019 ZetCode Ruby GTK Tutorial
40/65
5igure; 4bout(ialog
FontSelection&ialog
The 8ont2electionOialogis a dialog for selecting fonts. It is typically used in applications,
that do some te&t editing or formatting.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This e7ample wor)s with the# 8ont2electionOialog## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -8ont2electionOialog- signal,connect -destroy- do
Gt)main,'uitend
init,ui
set,de"ault,sie ;%% .% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
set,border,width %
Wlabel 5 Gt)::@abelnew -The only Eictory oEer loEe is "light- button 5 Gt)::9uttonnew -2elect "ont-
62
-
8/13/2019 ZetCode Ruby GTK Tutorial
41/65
buttonsignal,connect -clic)ed- do
on,clic)ed end
"i7 5 Gt)::8i7ednew
"i7put button %% ;% "i7put Wlabel ;% &% add "i7
end
de" on,clic)ed "dia 5 Gt)::8ont2electionOialognew -2elect "ont name- response 5 "diarun
i" response 55 Gt)::Oialog::R3201423,1K "ont,desc 5 0ango::8ontOescriptionnew "dia"ont,name i" "ont,desc
Wlabelmodi"y,"ont "ont,desc end end "diadestroy endend
Gt)init window 5 RubyppnewGt)main
In the code e&le, we ha#e a button and a label. 3e show the 8ont2electionOialog by
clic!ing on the button.
"dia 5 Gt)::8ont2electionOialognew -2elect "ont name-
3e create the 8ont2electionOialog.
i" response 55 Gt)::Oialog::R3201423,1K "ont,desc 5 0ango::8ontOescriptionnew "dia"ont,name i" "ont,desc Wlabelmodi"y,"ont "ont,desc endend
If we clic! on the "K button, the font of the label widget changes to the one, that we selected
in the dialog.
6/
-
8/13/2019 ZetCode Ruby GTK Tutorial
42/65
5igure; 5ont$election(ialog
ColorSelection&ialog
Color2electionOialog is a dialog for selecting a color.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This e7ample wor)s with the# Color2electionOialog## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -Color2electionOialog- signal,connect -destroy- do
Gt)main,'uitend
init,ui
set,de"ault,sie ;.% .%
set,window,position Gt)::+indow::012,C34T3R
show,all
60
-
8/13/2019 ZetCode Ruby GTK Tutorial
43/65
end
de" init,ui
set,border,width % Wlabel 5 Gt)::@abelnew -The only Eictory oEer loEe is "light-
button 5 Gt)::9uttonnew -2elect color-buttonsignal,connect -clic)ed- do
on,clic)ed end
"i7 5 Gt)::8i7ednew "i7put button %% ;% "i7put Wlabel ;% &% add "i7 end
de" on,clic)ed
cdia 5 Gt)::Color2electionOialognew -2elect color- response 5 cdiarun
i" response 55 Gt)::Oialog::R3201423,1K colorsel 5 cdiacolorsel color 5 colorselcurrent,color Wlabelmodi"y,"g Gt)::2TT3,41R?@ color end
cdiadestroy endend
Gt)init window 5 RubyppnewGt)main
The e&le is #ery similar to the pre#ious one. This time we change the color of the label.
cdia 5 Gt)::Color2electionOialognew -2elect color-
3e create the Color2electionOialog .
i" response 55 Gt)::Oialog::R3201423,1K colorsel 5 cdiacolorsel
color 5 colorselcurrent,color Wlabelmodi"y,"g Gt)::2TT3,41R?@ colorend
If the user pressed "K, we get the color #alue and modify the label>s color.
6:
-
8/13/2019 ZetCode Ruby GTK Tutorial
44/65
5igure; Color$election(ialog
In this part of the Ruby GTK tutorial, we presented dialogs.
Painting it! Cairo
In this part of the Ruby GTK tutorial, we will do some painting with the Cairo library.
Cairois a library for creating 0( #ector graphics. 3e can use it to draw our own widgets,charts or #arious effects or animations.
Colors
In the first e&le, we will wor! with colors. 4 color is an ob9ect representing a
combination of Red, Green, and 'lue ?RG'@ intensity #alues. Cairo #alid RG' #alues are in
the range 2 to /.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This program shows how to wor)# with colors in Cairo## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
66
-
8/13/2019 ZetCode Ruby GTK Tutorial
45/65
set,title -Colors-
signal,connect -destroy- doGt)main,'uit
end
init,ui
set,de"ault,sie ;B% %% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
Wdarea 5 Gt)::Orawingreanew
Wdareasignal,connect -e7poseeEent- do
on,e7pose end
addAWdareaD
end
de" on,e7pose
cr 5 Wdareawindowcreate,cairo,conte7tdraw,colors cr
end
de" draw,colors cr
crset,source,rgb %$ %$; %& crrectangle % . &% B% cr"ill
crset,source,rgb %& % % crrectangle ;% . &% B% cr"ill
crset,source,rgb % %& % crrectangle $.% . &% B% cr"ill endend
Gt)init window 5 RubyppnewGt)main
In our e&le, we will draw three rectangles and fill them with three different colors.
Wdarea 5 Gt)::Orawingreanew
3e will be doing our drawing operations on the Orawingreawidget.
Wdareasignal,connect -e7poseeEent- do
61
-
8/13/2019 ZetCode Ruby GTK Tutorial
46/65
on,e7poseend
3hen the window needs to be redrawn, the the e7poseeEentis triggered. In response to
this e#ent, we call the on,e7posemethod.
cr 5 Wdareawindowcreate,cairo,conte7t
3e create the cairo conte&t ob9ect from the Gd)+indowof the drawing area. The conte&t is an
ob9ect onto which we do all our drawings.
draw,colors cr
The actual drawing is delegated to the draw,colorsmethod.
crset,source,rgb %$ %$; %&
The set,source,rgbmethod sets a color for the cairo conte&t. The three parameters of the
method are the color intensity #alues.
crrectangle % . &% B%
3e draw a rectangle. The first two parameters are the &, y coordinates of the top left corner
of the rectangle. The last two parameters are the width and height of the rectangle.
cr"ill
3e fill the inside of the rectangle with the current color.
5igure; Colors
Basic shapes
The ne&t e&le draws some basic shapes onto the window.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This code e7ample draws basic shapes# with the Cairo library## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
6A
-
8/13/2019 ZetCode Ruby GTK Tutorial
47/65
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie
superset,title -9asic shapes-
signal,connect -destroy- doGt)main,'uit
end
init,ui
set,de"ault,sie ;&% $% set,window,position Gt)::+indow::012,C34T3R
show,all
endde" init,ui
Wdarea 5 Gt)::Orawingreanew
Wdareasignal,connect -e7poseeEent- doon,e7pose
end
addAWdareaD end
de" on,e7posecr 5 Wdareawindowcreate,cairo,conte7tdraw,shapes cr
end
de" draw,shapes cr
crset,source,rgb %B %B %B
crrectangle $% $% $% % crrectangle % $% % % cr"ill
crarc ;;% B% % % $J?ath::0> cr"ill
crarc &% B% % ?ath::0>/ ?ath::0> cr"ill
crtranslate $$% % crscale %H crarc % % .% % $J?ath::0> cr"ill endend
Gt)init window 5 Rubyppnew
6B
-
8/13/2019 ZetCode Ruby GTK Tutorial
48/65
Gt)main
In this e&le, we will create a rectangle, a s7uare, a circle, an arc and an ellipse. 3e draw
outlines in blue color, insides in white.
crrectangle $% $% $% %crrectangle % $% % %cr"ill
These lines draw a rectangle and a s7uare.
crarc ;;% B% % % $J?ath::0>cr"ill
-ere the arcmethod draws a full circle.
crtranslate $$% %
crscale %Hcrarc % % .% % $J?ath::0>cr"ill
The translatemethod mo#es the ob9ect to a specific point. If we want to draw an o#al, we
do some scaling first. -ere the scalemethod shrin!s the y a&is.
5igure; 'asic shapes
Transparent rectangles
Transparency is the 7uality of being able to see through a material. The easiest way to
understand transparency is to imagine a piece of glass or water. Technically, the rays of light
can go through the glass and this way we can see ob9ects behind the glass.
In computer graphics, we can achie#e transparency effects using alpha compositing. 4lpha
compositing is the process of combining an image with a bac!ground to create the
appearance of partial transparency. The composition process uses an alpha channel.
?wi!ipedia.org, answers.com@
6
-
8/13/2019 ZetCode Ruby GTK Tutorial
49/65
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This program shows transparent# rectangles using Cairo
## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -Transparent rectangles- signal,connect -destroy- doGt)main,'uit
end
init,ui
set,de"ault,sie .&% &% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,uiWdarea 5 Gt)::Orawingreanew
Wdareasignal,connect -e7poseeEent- doon,e7pose
end
addAWdareaD
end
de" on,e7pose
cr 5 Wdareawindowcreate,cairo,conte7t
"or i in A%D crset,source,rgba % % iJ% crrectangle .%Ji $% % % cr"ill end endend
Gt)init window 5 RubyppnewGt)main
In the e&le we will draw ten rectangles with different le#els of transparency.
6D
-
8/13/2019 ZetCode Ruby GTK Tutorial
50/65
crset,source,rgba % % iJ%
The last parameter of the set,source,rgbamethod is the alpha transparency.
5igure; Transparent rectangles
&onut
In the following e&le we create a comple& shape by rotating a bunch of ellipses.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This program creates a donut# with Cairo library## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -Oonut- signal,connect -destroy- do
Gt)main,'uitend
init,ui
set,de"ault,sie ;.% $.% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
Wdarea 5 Gt)::Orawingreanew
Wdareasignal,connect -e7poseeEent- doon,e7pose
end
addAWdareaD
12
-
8/13/2019 ZetCode Ruby GTK Tutorial
51/65
end
de" on,e7pose
cr 5 Wdareawindowcreate,cairo,conte7t
crset,line,width %.
w 5 allocationwidth h 5 allocationheight
crtranslate w/$ h/$ crarc % % $% % $J?ath::0> crstro)e
"or i in A;BD crsaEe crrotate iJ?ath::0>/;B crscale %;
crarc % % $% % $J?ath::0> crrestore crstro)e end endend
Gt)init window 5 RubyppnewGt)main
In this e&le, we create a donut. The shape resembles a coo!ie, hence the name donut.
crtranslate w/$ h/$crarc % % $% % $J?ath::0>crstro)e
In the beginning there is an ellipse.
"or i in A;BD crsaEe crrotate iJ?ath::0>/;B crscale %; crarc % % $% % $J?ath::0> crrestore
crstro)eend
4fter se#eral rotations, there is a donut.
1/
-
8/13/2019 ZetCode Ruby GTK Tutorial
52/65
5igure; (onut
&rawing text
In the ne&t e&le, we draw some te&t on the window.
#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial## This program draws te7t# using Cairo## author: jan bodnar# website: wwwetcodecom# last modi"ied: 6une $%%&
re'uire (gt)$(
class Rubypp * Gt)::+indow
de" initialie super
set,title -2oulmate-
signal,connect -destroy- doGt)main,'uit
end
init,ui
set,de"ault,sie ;H% $% set,window,position Gt)::+indow::012,C34T3R
show,all end
de" init,ui
Wdarea 5 Gt)::Orawingreanew
10
-
8/13/2019 ZetCode Ruby GTK Tutorial
53/65
Wdareasignal,connect -e7poseeEent- do
on,e7pose end
addAWdareaD
end
de" on,e7pose
cr 5 Wdareawindowcreate,cairo,conte7t
crset,source,rgb % % %
crselect,"ont,"ace -0urisa- Cairo::814T,2@4T,41R?@Cairo::814T,+3>GIT,41R?@
crset,"ont,sie ;
crmoEe,to $% ;% crshow,te7t -?ost relationships seem so transitory- crmoEe,to $% B% crshow,te7t -They(re all good but not the permanent one- crmoEe,to $% $% crshow,te7t -+ho doesn(t long "or someone to hold- crmoEe,to $% .% crshow,te7t -+ho )nows how to loEe without being told- crmoEe,to $% % crshow,te7t -2omebody tell me why >(m on my own- crmoEe,to $% $% crshow,te7t ->" there(s a soulmate "or eEeryone- end
end
Gt)init window 5 RubyppnewGt)main
3e display part of the lyrics from the atasha 'edingfields $oulmate song.
crselect,"ont,"ace -0urisa- Cairo::814T,2@4T,41R?@Cairo::814T,+3>GIT,41R?@
-ere we specify the font, that we use. urisa normal.
crset,"ont,sie ;
3e specify the si8e of the font.
crmoEe,to $% ;%
3e mo#e to the point, where we will draw the te&t.
crshow,te7t -?ost relationships seem so transitory-
The show,te7tmethod draws te&t onto the window.
1:
-
8/13/2019 ZetCode Ruby GTK Tutorial
54/65
5igure; $oulmate
In this chapter of the Ruby GTK tutorial, we were painting with Cairo library.
Custom idget
Most tool!its usually pro#ide only the most common widgets li!e buttons, te&t widgets,
sliders etc. o tool!it can pro#ide all possible widgets. rogrammers must create such
widgets by themsel#es. They do it by using the drawing tools pro#ided by the tool!it. There
are two possibilities. 4 programmer can modify or enhance an e&isting widget. "r he can
create a custom widget from scratch.
Burning widget
This is an e&le of a widget, that we create from scratch. This widget can be found in
#arious media burning applications, li!e ero 'urning R"M.
custom.rb#!/usr/bin/ruby
# ZetCode Ruby GTK tutorial#
# This e7ample creates a burning# custom widget## author: jan bodnar# website: etcodecom# last edited: 6une $%%&
re'uire (gt)$(
class 9urning * Gt)::Orawingrea
de" initialieAparentD Wparent 5 parent
superAD
16
-
8/13/2019 ZetCode Ruby GTK Tutorial
55/65
Wnum 5 X -H.- -.%- -$$.- -;%%-
-;H.- -.%- -.$.- -B%%- -BH.- Y
set,sie,re'uest ;% signal,connect -e7poseeEent- do
e7pose end end
de" e7pose
cr 5 windowcreate,cairo,conte7t draw,widget cr
end
de" draw,widget cr
crset,line,width %
crselect,"ont,"aceA-Courier-Cairo::814T,2@4T,41R?@ Cairo::814T,+3>GIT,41R?@D
crset,"ont,sie
width 5 allocationwidth
Wcur,width 5 Wparentget,cur,Ealue
step 5 Awidth / %%Dround
till 5 Awidth / H.%%D J Wcur,width "ull 5 Awidth / H.%%D J H%%
i" Wcur,width F5 H%%
crset,source,rgbA% % %H$D crrectangleA% % "ull ;%D crclip crpaint crreset,clip
crset,source,rgbA% %B %BD crrectangleA"ull % till"ull ;%D crclip crpaint crreset,clip
else crset,source,rgb % % %H$ crrectangle % % till ;% crclip crpaint crreset,clip end
crset,source,rgbA%;. %; %$D
"or i in AWnumlengthD
11
-
8/13/2019 ZetCode Ruby GTK Tutorial
56/65
crmoEe,to iJstep % crline,to iJstep . crstro)e
te 5 crte7t,e7tents WnumXiY crmoEe,to iJsteptewidth/$ .
crte7t,path WnumXiY crstro)e end
endend
class Rubypp * Gt)::+indow de" initialie super
set,title -9urning- signal,connect -destroy- do
Gt)main,'uitend
set,sie,re'uest ;.% $%%set,window,position Gt)::+indow::012,C34T3R
Wcur,Ealue 5 %
Ebo7 5 Gt)::=9o7new "alse $
scale 5 Gt)::I2calenew
scaleset,range % H.% scaleset,digits %
scaleset,sie,re'uest B% ;. scaleset,Ealue Wcur,Ealue
scalesignal,connect -Ealuechanged- do MwM on,changedAwD end
"i7 5 Gt)::8i7ednew "i7put scale .% .%
Ebo7pac),start "i7
Wburning 5 9urningnewAsel"D Ebo7pac),start Wburning "alse "alse %
add Ebo7 show,all end
de" on,changed widget
Wcur,Ealue 5 widgetEalue Wburning'ueue,draw end
de" get,cur,Ealue return Wcur,Ealue endend
1A
-
8/13/2019 ZetCode Ruby GTK Tutorial
57/65
Gt)init window 5 RubyppnewGt)main
3e put a Orawingreaon the bottom of the window and draw the entire widget manually.
4ll the important code resides in the draw,widgetwhich is called from the e7posemethod
of the 'urning class. This widget shows graphically the total capacity of a medium and the
free space a#ailable to us. The widget is controlled by a scale widget. The minimum #alue of
our custom widget is 2, the ma&imum is B12. If we reach #alue B22, we began drawing in red
colour. This normally indicates o#erburning.
Wnum 5 X -H.- -.%- -$$.- -;%%--;H.- -.%- -.$.- -B%%- -BH.- Y
These numbers are shown on the burning widget. They show the capacity of the medium.
Wcur,width 5 Wparentget,cur,Ealue
5rom the parent widget, we get the current #alue of the scale widget.
till 5 Awidth / H.%%D J Wcur,width"ull 5 Awidth / H.%%D J H%%
3e use the width#ariable to do the transformations. 'etween the #alues of the scale and the
custom widget>s measures. ote that we use floating point #alues. 3e get greater precision in
drawing. The tillparameter determines the total si8e to be drawn. This #alue comes from
the slider widget. It is a proportion of the whole area. The "ullparameter determines the
point, where we begin to draw in red color.
crset,source,rgbA% % %H$DcrrectangleA% % "ull ;%Dcrclipcrpaintcrreset,clip
3e draw a yellow rectangle up to point, where the medium is full.
te 5 crte7t,e7tents WnumXiYcrmoEe,to iJsteptewidth/$ .
crte7t,path WnumXiYcrstro)e
This code here draws the numbers on the burning widget. 3e calculate the te&t e&tents to
position the te&t correctly.
de" on,changed widget
Wcur,Ealue 5 widgetEalue Wburning'ueue,drawend
3e get the #alue from the scale widget, store it in the Wcur,Ealue#ariable for later use. 3eredraw the burning widget.
1B
-
8/13/2019 ZetCode Ruby GTK Tutorial
58/65
5igure; 'urning widget
In this chapter, we created a custom widget in GTK and Ruby programming language.
"ibbles
In this part of the Ruby GTK programming tutorial, we will create a ibbles game clone.
"ibblesis an older classic #ideo game. It was first created in late B2s. %ater it was brought to
Cs. In this game the player controls a sna!e. The ob9ecti#e is to eat as many apples as
possible.
-
8/13/2019 ZetCode Ruby GTK Tutorial
59/65
init,game end
de" on,timer
i" WinGame
chec),apple chec),collision moEe 'ueue,draw return true else return "alse end end
de" init,game
Wle"t 5 "alse
Wright 5 true Wup 5 "alse Wdown 5 "alse WinGame 5 true Wdots 5 ;
"or i in A%WdotsD Q7XiY 5 .% i J % QyXiY 5 .% end
begin Wdot 5 Cairo::>mage2ur"ace"rom,png -dotpng-
Whead 5 Cairo::>mage2ur"ace"rom,png -headpng- Wapple 5 Cairo::>mage2ur"ace"rom,png -applepng- rescue 37ception 5F e puts -cannot load images- e7it end
locate,apple G@ib::TimeoutaddA%%D S on,timer U
end
de" on,e7pose
cr 5 windowcreate,cairo,conte7t
i" WinGame draw,objects cr else game,oEer cr end
end
de" draw,objects cr
crset,source,rgb % % % crpaint
1D
-
8/13/2019 ZetCode Ruby GTK Tutorial
60/65
crset,source Wapple Wapple,7 Wapple,y crpaint
"or in A%WdotsD i" 55 %
crset,source Whead Q7XY QyXY
crpaint else crset,source Wdot Q7XY QyXY crpaint end
end end
de" game,oEer cr
w 5 allocationwidth / $ h 5 allocationheight / $
crset,"ont,sie . te 5 crte7t,e7tents -Game 1Eer-
crset,source,rgb B..;. B..;. B..;.
crmoEe,to w tewidth/$ h crshow,te7t -Game 1Eer-
end
de" chec),apple
i" Q7X%Y 55 Wapple,7 and QyX%Y 55 Wapple,yWdots 5 Wdots L locate,apple end end
de" moEe
5 Wdots
while F % Q7XY 5 Q7XA DY QyXY 5 QyXA DY 5 end
i" Wle"t Q7X%Y 5 O1T,2>Z3 end
i" WrightQ7X%Y L5 O1T,2>Z3
end
i" Wup QyX%Y 5 O1T,2>Z3 end
i" Wdown
A2
-
8/13/2019 ZetCode Ruby GTK Tutorial
61/65
QyX%Y L5 O1T,2>Z3 end
end
de" chec),collision
5 Wdots
while F % i" F and Q7X%Y 55 Q7XY and QyX%Y 55 QyXY WinGame 5 "alse end 5 end
i" QyX%Y F I3>GIT O1T,2>Z3 WinGame 5 "alse end
i" QyX%Y * % WinGame 5 "alse end
i" Q7X%Y F +>OTI O1T,2>Z3 WinGame 5 "alse end
i" Q7X%Y * % WinGame 5 "alse end
end
de" locate,apple
r 5 randAR4O,012D Wapple,7 5 r J O1T,2>Z3 r 5 randAR4O,012D Wapple,y 5 r J O1T,2>Z3 end
de" on,)ey,down eEent
)ey 5 eEent)eyEal
i" )ey 55 Gd)::KeyEal::GOK,@e"t and not Wright Wle"t 5 true Wup 5 "alse Wdown 5 "alse end
i" )ey 55 Gd)::KeyEal::GOK,Right and not Wle"t Wright 5 true Wup 5 "alse Wdown 5 "alse end
i" )ey 55 Gd)::KeyEal::GOK,Vp and not Wdown Wup 5 true Wright 5 "alse
A/
-
8/13/2019 ZetCode Ruby GTK Tutorial
62/65
Wle"t 5 "alse end
i" )ey 55 Gd)::KeyEal::GOK,Oown and not Wup Wdown 5 true Wright 5 "alse
Wle"t 5 "alse end endend
5irst we will define some globals used in our game.
The 3I(T- and -
-
8/13/2019 ZetCode Ruby GTK Tutorial
63/65
de" chec),apple
i" Q7X%Y 55 Wapple,7 and QyX%Y 55 Wapple,yWdots 5 Wdots L
locate,apple end
end
The chec),applemethod chec!s, if the sna!e has hit the apple ob9ect. If so, we add another
sna!e 9oint and call the locate,applemethod, which randomly places a new apple ob9ect.
In the moEemethod we ha#e the !ey algorithm of the game. To understand it, loo! at how the
sna!e is mo#ing. Jou control the head of the sna!e. Jou can change its direction with the
cursor !eys. The rest of the 9oints mo#e one position up the chain. The second 9oint mo#es
where the first was, the third 9oint where the second was etc.
while F %
Q7XY 5 Q7XA DY QyXY 5 QyXA DY 5 end
This code mo#es the 9oints up the chain.
i" Wle"t Q7X%Y 5 O1T,2>Z3end
Mo#e the head to the left.
In the chec),collisionmethod, we determine if the sna!e has hit itself or one of the walls.
while F % i" F and Q7X%Y 55 Q7XY and QyX%Y 55 QyXY WinGame 5 "alse end 5 end
5inish the game, if the sna!e hits one of its 9oints with the head.
i" QyX%Y F I3>GIT O1T,2>Z3 WinGame 5 "alseend
5inish the game, if the sna!e hits the bottom of the 'oard.
The locate,applemethod locates an apple randomly on the board.
r 5 randAR4O,012D
3e get a random number from 2 to R4(H"$ E /.
Wapple,7 5 r J O1T,2>Z3
A:
-
8/13/2019 ZetCode Ruby GTK Tutorial
64/65
Wapple,y 5 r J O1T,2>Z3
These line set the &, y coordinates of the apple ob9ect.
i" WinGame chec),apple chec),collision moEe 'ueue,draw return trueelse return "alseend
-
8/13/2019 ZetCode Ruby GTK Tutorial
65/65
add Wboard
set,de"ault,sie ;%% $H% set,window,position Gt)::+indow::012,C34T3R show,all
endde" on,)ey,down widget eEent
)ey 5 eEent)eyEal Wboardon,)ey,down eEent endend
Gt)init window 5 RubyppnewGt)main
In this class, we set up the ibbles game.
de" on,)ey,down widget eEent
)ey 5 eEent)eyEal Wboardon,)ey,down eEentend
In this class, we catch the !ey press e#ents. 4nd delegate the processing to the on,)ey,down
method of the board class.
5igure; ibbles