ZetCode Ruby GTK Tutorial
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.
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: www !etcode com last modi"ied: #pril $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -Center-
signal,connect -destroy- do Gt) main,'uit end set,de"ault,si!e $.%/ $%% set,window,position Gt)::+indow::012,C34T3R show end end
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 Ruby#pp * Gt)::+indow
The destroy e#ent is triggered, when we clic! on the close button in the titlebar. "r press 4lt * 56. The method main,'uit 7uits the application for good.
set,de"ault,si!e $.%/ $%%
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: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -Tooltipssignal,connect -destroy- do Gt) main,'uit end "i7ed 5 Gt)::8i7ed new add "i7ed button 5 Gt)::9utton new -9uttonbutton set,si!e,re'uest :%/ ;. button set,tooltip,te7t -9utton widget"i7ed put button/ .%/ .% set,tooltip,te7t -+indow widgetset,de"ault,si!e $.%/ $%% set,window,position Gt)::+indow::012,C34T3R show,all end end
The e&le creates a window. If we ho#er a mouse pointer o#er the area of the window, a tooltip pops up.
button set,tooltip,te7t -9utton widget-
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: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -<uit buttonsignal,connect -destroy- do Gt) main,'uit end init,ui end show,all
de" init,ui "i7ed 5 Gt)::8i7ed new add "i7ed button 5 Gt)::9utton new -<uitbutton set,si!e,re'uest :%/ ;. button signal,connect -clic)ed- do
end
Gt) main,'uit
end end
3e use a 9utton widget. This is a #ery common widget. It shows a te&t label, image or both.
init,ui
3e ha#e two options. <ither to call show on all widgets, or to call show,all, which shows the container and all its children.
button 5 Gt)::9utton new -<uit-
3e put the 7uit button into the fi&ed container at &=12, y=12.
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, =9o7 and Table.
Fixed
The 8i7ed container 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: www !etcode com last modi"ied: 6une $%%&
set,title -8i7edsignal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e ;%%/ $:% set,window,position Gt)::+indow::012,C34T3R end show,all
de" init,ui modi"y,bg Gt)::2T#T3,41R?#@/ Gd)::Color newABC%%/ BC%%/ BCC%D begin bardejoE 5 Gd)::0i7bu" new -bardejoE jpgrotunda 5 Gd)::0i7bu" new -rotunda jpgmincol 5 Gd)::0i7bu" new -mincol jpgrescue >13rror 5F e puts e puts -cannot load imagese7it end imageG 5 Gt)::>mage new bardejoE image$ 5 Gt)::>mage new rotunda image; 5 Gt)::>mage new mincol "i7ed 5 Gt)::8i7ed new "i7ed put imageG/ $%/ $% "i7ed put image$/ C%/ GB% "i7ed put image;/ GH%/ .% add "i7ed end end Gt) init window 5 Ruby#pp new Gt) 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)::2T#T3,41R?#@/ Gd)::Color newABC%%/ BC%%/ BCC%D
5or better #isual e&perience, we change the bac!ground color to dar! gray.
bardejoE 5 Gd)::0i7bu" new -bardejoE jpg-
The >mage is a widget, that is used to display images. It ta!es 0i7bu" ob9ect in the constructor.
"i7ed 5 Gt)::8i7ed new
5igure; 5i&ed
Buttons
The #lignment container 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 hori!ontal and Eertical bo7es author: jan bodnar website: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$(
class Ruby#pp * Gt)::+indow de" initiali!e super set,title -9uttonssignal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e $B%/ G.% set,window,position Gt)::+indow::012,C34T3R show,all end de" init,ui Ebo7 5 Gt)::=9o7 new "alse/ . hbo7 5 Gt)::I9o7 new true/ ; Ealign 5 Gt)::#lignment new %/ G/ %/ % Ebo7 pac),start Ealign o) 5 Gt)::9utton new -1Ko) set,si!e,re'uest H%/ ;% close 5 Gt)::9utton new -Closehbo7 add o) hbo7 add close halign 5 Gt)::#lignment new G/ %/ %/ % halign add hbo7 Ebo7 pac),start halign/ "alse/ "alse/ ; end end Gt) init window 5 Ruby#pp new Gt) main add Ebo7
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)::#lignment new %/ G/ %/ %
hbo7 5 Gt)::I9o7 new true/ ; o) 5 Gt)::9utton new -1Ko) set,si!e,re'uest H%/ ;% close 5 Gt)::9utton new -Closehbo7 add o) hbo7 add close
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 Table widget 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: www !etcode com last modi"ied: 6une $%%&
/2
set,title -Calculatorsignal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e ;%%/ $.% set,window,position Gt)::+indow::012,C34T3R end show,all
de" init,ui Ebo7 5 Gt)::=9o7 new "alse/ $ mb 5 Gt)::?enu9ar new "ilemenu 5 Gt)::?enu new "ile 5 Gt)::?enu>tem new -8ile"ile set,submenu "ilemenu mb append "ile Ebo7 pac),start mb/ "alse/ "alse/ % table 5 Gt)::Table new ./ C/ true table table table table table table table table table table table table table table table table table table table table attach attach attach attach attach attach attach attach attach attach attach attach attach attach attach attach attach attach attach attach Gt)::9utton newA-Cls-D/ %/ G/ %/ G Gt)::9utton newA-9c)-D/ G/ $/ %/ G Gt)::@abel new/ $/ ;/ %/ G Gt)::9utton newA-Close-D/ ;/ C/ %/ G Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton newA-H-D/ newA-:-D/ newA-&-D/ newA-/-D/ newA-C-D/ newA-.-D/ newA-B-D/ newA-J-D/ newA-G-D/ newA-$-D/ newA-;-D/ newA-K-D/ newA-%-D/ newA- -D/ newA-5-D/ newA-L-D/ %/ G/ $/ ;/ %/ G/ $/ ;/ %/ G/ $/ ;/ %/ G/ $/ ;/ G/ $/ ;/ C/ G/ $/ ;/ C/ G/ $/ ;/ C/ G/ $/ ;/ C/ G/ G/ G/ G/ $/ $/ $/ $/ ;/ ;/ ;/ ;/ C/ C/ C/ C/ $ $ $ $ ; ; ; ; C C C C . . . .
Ebo7 pac),start Gt)::3ntry new/ "alse/ "alse/ % Ebo7 pac),end table/ true/ true/ % add Ebo7 end end
//
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.
table attach Gt)::9utton newA-Cls-D/ %/ G/ %/ G
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.
Ebo7 pac),end table/ true/ true/ %
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(<.
#!/usr/bin/ruby # # # # # # ZetCode Ruby GTK tutorial This is a more complicated layout e7ample +e use #lignment and Table widgets author: jan bodnar
/0
# website: www !etcode com # last modi"ied: 6une $%%& re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -+indowssignal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e ;%%/ $.% set,window,position Gt)::+indow::012,C34T3R show,all end de" init,ui set,border,width G. table 5 Gt)::Table new :/ C/ "alse table set,column,spacings ; title 5 Gt)::@abel new -+indowshalign 5 Gt)::#lignment new %/ %/ %/ % halign add title table attachAhalign/ %/ G/ %/ G/ Gt)::8>@@/ Gt)::8>@@/ %/ %D "rame 5 Gt)::8rame new table attachA"rame/ %/ $/ G/ ;/ Gt)::8>@@ M Gt)::3N0#4O/ Gt)::8>@@ M Gt)::3N0#4O/ G/ GD actiEate 5 Gt)::9utton new -#ctiEateactiEate set,si!e,re'uest .%/ ;% table attachAactiEate/ ;/ C/ G/ $/ Gt)::8>@@/ Gt)::2IR>4K/ G/ GD Ealign 5 Gt)::#lignment new %/ %/ %/ % close 5 Gt)::9utton new -Closeclose set,si!e,re'uest H%/ ;% Ealign add close table set,row,spacing G/ ; table attachAEalign/ ;/ C/ $/ ;/ Gt)::8>@@/ Gt)::8>@@ M Gt)::3N0#4O/ G/ GD halign$ 5 Gt)::#lignment new %/ G/ %/ % help 5 Gt)::9utton new -Ielphelp set,si!e,re'uest H%/ ;% halign$ add help table set,row,spacing ;/ B
/:
table attachAhalign$/ %/ G/ C/ ./ Gt)::8>@@/ Gt)::8>@@/ %/ %D o) 5 Gt)::9utton new -1Ko) set,si!e,re'uest H%/ ;% table attachAo)/ ;/ C/ C/ ./ Gt)::8>@@/ Gt)::8>@@/ %/ %D end end Gt) init window 5 Ruby#pp new Gt) main add table
The code e&le shows, how we can create a similar window in Ruby GTK.
table 5 Gt)::Table new :/ C/ "alse table set,column,spacings ;
The e&le is based on the Table container. There will be :p& space between columns.
title 5 Gt)::@abel new -+indowshalign 5 Gt)::#lignment new %/ %/ %/ % halign add title table attachAhalign/ %/ G/ %/ G/ 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 the Table container.
"rame 5 Gt)::8rame new table attachA"rame/ %/ $/ G/ ;/ Gt)::8>@@ M Gt)::3N0#4O/ Gt)::8>@@ M Gt)::3N0#4O/ G/ GD
The frame #iew widget spans two rows and two columns.
Ealign 5 Gt)::#lignment new %/ %/ %/ % close 5 Gt)::9utton new -Closeclose set,si!e,re'uest H%/ ;% Ealign add close table set,row,spacing G/ ; table attachAEalign/ ;/ C/ $/ ;/ Gt)::8>@@/ Gt)::8>@@ M Gt)::3N0#4O/ G/ GD
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
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 minimum le#el. More speciali8ed widgets are created as custom GTK widgets.
CheckButton
is 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.
Chec)9utton #!/usr/bin/ruby # # # # # # # # ZetCode Ruby GTK tutorial This program toggles the title o" the window with the Chec)9utton widget author: jan bodnar website: www !etcode com last modi"ied: #pril $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -Chec)9uttonsignal,connect -destroy- do
/1
end
Gt) main,'uit
init,ui set,de"ault,si!e $.%/ $%% set,window,position Gt)::+indow::012,C34T3R show,all end de" init,ui "i7ed 5 Gt)::8i7ed new add "i7ed cb cb cb cb end 5 Gt)::Chec)9utton new -2how titleset,actiEe true set,can,"ocus "alse signal,connectA-clic)ed-D do MwM on,clic)edAwD
"i7ed put cb/ .%/ .% end de" on,clic)ed sender i" sender actiEeP sel" set,title -Chec) 9uttonelse sel" set,title -end end end
3e will display a title in the titlebar of the window, depending on the state of the Chec)9utton.
cb 5 Gt)::Chec)9utton new -2how titleChec)9utton
widget is created.
cb set,actiEe true
/A
5igure; Chec!'utton
abel
The @abel widget shows te&t.
#!/usr/bin/ruby # # # # # # # ZetCode Ruby GTK tutorial This e7ample demonstrates the @abel widget author: jan bodnar website: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( Qlyrics 5 RS?eet you downstairs in the bar and heard your rolled up sleeEes and your s)ull tKshirt Tou say why did you do it with him todayP and sni"" me out li)e > was Tan'ueray cause you(re my "ella/ my guy hand me your stella and "ly by the time >(m out the door you tear men down li)e Roger ?oore > cheated mysel" li)e > )new > would > told ya/ > was trouble you )now that >(m no goodU class Ruby#pp * Gt)::+indow de" initiali!e super set,title -Tou )now >(m no Goodsignal,connect -destroy- do Gt) main,'uit
/B
end init,ui set,de"ault,si!e $.%/ $%% set,window,position Gt)::+indow::012,C34T3R show,all end de" init,ui set,border,width G% label 5 Gt)::@abel new Qlyrics add label end end
/C
!ntr"
The 3ntry is 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: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -3ntrysignal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e $.%/ $%% set,window,position Gt)::+indow::012,C34T3R end show,all
de" init,ui "i7ed 5 Gt)::8i7ed new label 5 Gt)::@abel new "i7ed put label/ B%/ C% entry 5 Gt)::3ntry new "i7ed put entry/ B%/ G%% entry signal,connect -)eyKreleaseKeEent- do Mw/ eM on,)ey,releaseAw/ e/ labelD end addA"i7edD end de" on,)ey,release sender/ eEent/ label label set,te7t sender te7t end -
end
Gt) init
/D
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)::3ntry new 3ntry
widget is created.
3e get the te&t from the 3ntry widget and set it to the label.
#mage
The >mage widget shows an image.
#!/usr/bin/ruby # # # # # # # ZetCode Ruby GTK tutorial This e7ample demonstrates the >mage widget author: jan bodnar website: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$(
02
class Ruby#pp * Gt)::+indow de" initiali!e super set,title -Red Roc)signal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e $.%/ $%% set,window,position Gt)::+indow::012,C34T3R show,all end de" init,ui set,border,width $ begin image 5 Gt)::>mage new -redroc) pngrescue puts -cannot load imagee7it end add image end end Gt) init window 5 Ruby#pp new Gt) main
The >mage widget is created. I" operations are error prone, so we handle the possible e&ceptions.
add image
0/
ComboBox
Combo9o7
#!/usr/bin/ruby # # # # # # # ZetCode Ruby GTK tutorial This e7ample demonstrates the Combo9o7 widget author: jan bodnar website: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -Combo9o7signal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e $.%/ $%% set,window,position Gt)::+indow::012,C34T3R show,all end de" init,ui "i7ed 5 Gt)::8i7ed new label 5 Gt)::@abel new (K(
00
"i7ed put label/ .%/ GC% cb 5 Gt)::Combo9o7 new cb signal,connect -changed- do Mw/ eM on,changedAw/ e/ labelD end cb cb cb cb cb append,te7t append,te7t append,te7t append,te7t append,te7t (Vbuntu( (?andriEa( (Redhat( (Gento( (?int(
"i7ed put cb/ .%/ ;% add "i7ed end de" on,changed sender/ eEent/ label label set,label sender actiEe,te7t end end Gt) init window 5 Ruby#pp new Gt) 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)::Combo9o7 new
Inside the on,changed method, we get the selected te&t out of the combo bo& and set it to the label.
0:
5igure; Combo'o& In this chapter of the Ruby GTK tutorial, we showed some basic widgets.
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: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -2imple menusignal,connect -destroy- do Gt) main,'uit
06
end init,ui set,de"ault,si!e $.%/ $%% set,window,position Gt)::+indow::012,C34T3R show,all end de" init,ui modi"y,bg Gt)::2T#T3,41R?#@/ Gd)::Color newABC%%/ BC%%/ BCC%D mb 5 Gt)::?enu9ar new "ilemenu 5 Gt)::?enu new "ilem 5 Gt)::?enu>tem new -8ile"ilem set,submenu "ilemenu e7it 5 Gt)::?enu>tem new -37ite7it signal,connect -actiEate- do Gt) main,'uit end "ilemenu append e7it mb append "ilem Ebo7 5 Gt)::=9o7 new "alse/ $ Ebo7 pac),start mb/ "alse/ "alse/ % end end Gt) init window 5 Ruby#pp new Gt) main add Ebo7
01
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&.
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: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -2ubmenusignal,connect -destroy- do Gt) main,'uit end init,ui
0A
de" init,ui modi"y,bg Gt)::2T#T3,41R?#@/ Gd)::Color newABC%%/ BC%%/ BCC%D mb 5 Gt)::?enu9ar new "ilemenu 5 Gt)::?enu new "ilem 5 Gt)::?enu>tem new -8ile"ilem set,submenu "ilemenu mb append "ilem imenu 5 Gt)::?enu new importm 5 Gt)::?enu>tem new ->mportimportm set,submenu imenu inews 5 Gt)::?enu>tem new ->mport news "eed iboo)mar)s 5 Gt)::?enu>tem new ->mport boo)mar)s imail 5 Gt)::?enu>tem new ->mport mail imenu append inews imenu append iboo)mar)s imenu append imail "ilemenu append importm e7it 5 Gt)::?enu>tem new -37ite7it signal,connect -actiEate- do Gt) main,'uit end "ilemenu append e7it Ebo7 5 Gt)::=9o7 new "alse/ $ Ebo7 pac),start mb/ "alse/ "alse/ % end end Gt) init window 5 Ruby#pp new Gt) main add Ebo7 -
$ubmenu creation.
imenu 5 Gt)::?enu new
4 submenu is a ?enu.
importm 5 Gt)::?enu>tem new ->mportimportm set,submenu imenu
0B
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. Accelerators are !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: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title ->mage menusignal,connect -destroy- do Gt) main,'uit end
0C
init,ui set,de"ault,si!e $.%/ $%% set,window,position Gt)::+indow::012,C34T3R show,all end de" init,ui modi"y,bg Gt)::2T#T3,41R?#@/ Gd)::Color newABC%%/ BC%%/ BCC%D mb 5 Gt)::?enu9ar new "ilemenu 5 Gt)::?enu new "ilem 5 Gt)::?enu>tem new -8ile"ilem set,submenu "ilemenu agr 5 Gt)::#ccelGroup new add,accel,group agr newi 5 Gt)::>mage?enu>tem new Gt)::2toc)::43+/ agr )ey/ mod 5 Gt)::#ccelerator parse -4newi add,acceleratorA-actiEate-/ agr/ )ey/ mod/ Gt)::#CC3@,=>2>9@3D "ilemenu append newi openm 5 Gt)::>mage?enu>tem new Gt)::2toc)::1034/ agr )ey/ mod 5 Gt)::#ccelerator parse -1openm add,acceleratorA-actiEate-/ agr/ )ey/ mod/ Gt)::#CC3@,=>2>9@3D "ilemenu append openm sep 5 Gt)::2eparator?enu>tem new "ilemenu append sep e7it 5 Gt)::>mage?enu>tem new Gt)::2toc)::<V>T/ agr )ey/ mod 5 Gt)::#ccelerator parse -<e7it add,acceleratorA-actiEate-/ agr/ )ey/ mod/ Gt)::#CC3@,=>2>9@3D e7it signal,connect -actiEate- do Gt) main,'uit end "ilemenu append e7it mb append "ilem Ebo7 5 Gt)::=9o7 new "alse/ $ Ebo7 pac),start mb/ "alse/ "alse/ % add Ebo7 end end
0D
"ur e&le shows a tople#el menu item with three suble#el menu items. <ach of the menu items has a image and an accelerator. The accelerator for the 7uit menu item is acti#e.
agr 5 Gt)::#ccelGroup new add,accel,group agr
To wor! with accelerators, we create a global #ccelGroup ob9ect. It will be used later.
newi 5 Gt)::>mage?enu>tem new Gt)::2toc)::43+/ agr )ey/ mod 5 Gt)::#ccelerator parse -4newi add,acceleratorA-actiEate-/ agr/ )ey/ mod/ Gt)::#CC3@,=>2>9@3D "ilemenu append newi
is created. The image comes from the stoc! of images. 3e create also a Ctrl*. accelerator.
>mage?enu>tem sep 5 Gt)::2eparator?enu>tem new "ilemenu append 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: www !etcode com last modi"ied: 6une $%%&
:2
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -Toolbarsignal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e $.%/ $%% set,window,position Gt)::+indow::012,C34T3R show,all end de" init,ui toolbar 5 Gt)::Toolbar new toolbar set,toolbar,style Gt)::Toolbar::2tyle::>C142 newtb 5 Gt)::Tool9utton new Gt)::2toc)::43+ opentb 5 Gt)::Tool9utton new Gt)::2toc)::1034 saEetb 5 Gt)::Tool9utton new Gt)::2toc)::2#=3 sep 5 Gt)::2eparatorTool>tem new 'uittb 5 Gt)::Tool9utton new Gt)::2toc)::<V>T toolbar toolbar toolbar toolbar toolbar insert insert insert insert insert %/ G/ $/ ;/ C/ newtb opentb saEetb sep 'uittb
'uittb signal,connect -clic)ed- do Gt) main,'uit end Ebo7 5 Gt)::=9o7 new "alse/ $ Ebo7 pac),start toolbar/ "alse/ "alse/ % end end Gt) init window 5 Ruby#pp new Gt) main addAEbo7D
4 Tool9utton with an image from stoc! is created. The image comes from the builtEin stoc! of images.
sep 5 Gt)::2eparatorTool>tem new
This is a separator. It can be used to put toolbar buttons into logical groups.
toolbar insert %/ newtb toolbar insert G/ opentb
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: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$(
:0
class Ruby#pp * Gt)::+indow de" initiali!e super set,title -Vndo redosignal,connect -destroy- do Gt) main,'uit end Wcount 5 $ init,ui set,de"ault,si!e $.%/ $%% set,window,position Gt)::+indow::012,C34T3R show,all end de" init,ui toolbar 5 Gt)::Toolbar new toolbar set,toolbar,style Gt)::Toolbar::2tyle::>C142 Wundo 5 Gt)::Tool9utton new Gt)::2toc)::V4O1 Wredo 5 Gt)::Tool9utton new Gt)::2toc)::R3O1 sep 5 Gt)::2eparatorTool>tem new 'uit 5 Gt)::Tool9utton new Gt)::2toc)::<V>T toolbar toolbar toolbar toolbar insert insert insert insert %/ G/ $/ ;/ Wundo Wredo sep 'uit
Wundo signal,connect -clic)ed- do on,undo end Wredo signal,connect -clic)ed- do on,redo end 'uit signal,connect -clic)ed- do Gt) main,'uit end Ebo7 5 Gt)::=9o7 new "alse/ $ Ebo7 pac),start toolbar/ "alse/ "alse/ % sel" add Ebo7 end de" on,undo Wcount 5 Wcount K G i" Wcount *5 %
::
de" on,redo Wcount 5 Wcount L G i" Wcount F5 . Wredo set,sensitiEe "alse Wundo set,sensitiEe true end
end end
"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 $
3e ha#e two tool buttons. Undo and redo tool buttons. Images come from the stoc! resources.
Wundo signal,connect -clic)ed- do on,undo end
:6
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 Gtal!G 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: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -?essagessignal,connect -destroy- do
:1
end
Gt) main,'uit
de" init,ui table 5 Gt)::Table new $/ $/ true in"o warn 'ues erro 5 5 5 5 Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton new new new new ->n"ormation-+arning-<uestion-3rror-
in"o signal,connect -clic)ed- do on,in"o end warn signal,connect -clic)ed- do on,warn end 'ues signal,connect -clic)ed- do on,'ues end erro signal,connect -clic)ed- do on,erro end table table table table attach attach attach attach in"o/ warn/ 'ues/ erro/ %/ G/ %/ G/ G/ $/ G/ $/ %/ %/ G/ G/ G G $ $
add table end de" on,in"o md 5 Gt)::?essageOialog newAsel"/ Gt)::Oialog::O32TR1T,+>TI,0#R34T/ Gt)::?essageOialog::>481/ Gt)::?essageOialog::9VTT142,C@123/ -Oownload completed-D md run md destroy end de" on,erro md 5 Gt)::?essageOialog newAsel"/ Gt)::Oialog::?1O#@ M Gt)::Oialog::O32TR1T,+>TI,0#R34T/ Gt)::?essageOialog::3RR1R/ Gt)::?essageOialog::9VTT142,C@123/ -3rror loading "ile-D md run md destroy end
:A
de" on,'ues md 5 Gt)::?essageOialog newAsel"/ Gt)::Oialog::O32TR1T,+>TI,0#R34T/ Gt)::?essageOialog::<V32T>14/ Gt)::?essageOialog::9VTT142,C@123/ -#re you sure to 'uitP-D md run md destroy end de" on,warn md 5 Gt)::?essageOialog newAsel"/ Gt)::Oialog::O32TR1T,+>TI,0#R34T/ Gt)::?essageOialog::+#R4>4G/ Gt)::?essageOialog::9VTT142,C@123/ -Vnallowed operation-D md run md destroy end
end
In our e&le, we will show four !inds of message dialogs. Information, 3arning, )uestion and <rror message dialogs.
in"o warn 'ues erro 5 5 5 5 Gt)::9utton Gt)::9utton Gt)::9utton Gt)::9utton new new new new ->n"ormation-+arning-<uestion-3rror-
3e ha#e four buttons. <ach of these buttons will show a different !ind of message dialog.
de" on,in"o md 5 Gt)::?essageOialog newAsel"/ Gt)::Oialog::O32TR1T,+>TI,0#R34T/ Gt)::?essageOialog::>481/ Gt)::?essageOialog::9VTT142,C@123/ -Oownload completed-D md run md destroy end
If we clic! on the info button, the Information dialog is displayed. The Gt)::?essageOialog::>481 specifies the type of the dialog. The Gt)::?essageOialog::9VTT142,C@123 specifies the button to be displayed in the dialog. The last parameter is the message dislayed. The dialog is displayed with the run method. The programmer must also call either the destroy or the hide method.
:B
About&ialog
The #boutOialog displays information about the application. #boutOialog can 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: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -#bout dialogsignal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e ;%%/ G.% set,window,position Gt)::+indow::012,C34T3R show,all end
:C
de" init,ui button 5 Gt)::9utton new -#boutbutton set,si!e,re'uest :%/ ;% button signal,connect -clic)ed- do on,clic)ed end "i7 5 Gt)::8i7ed new "i7 put button/ $%/ $% add "i7 end de" on,clic)ed about 5 Gt)::#boutOialog new about set,program,name -9atteryabout set,Eersion -% Gabout set,copyright -AcD 6an 9odnarabout set,comments -9attery is a simple tool "or battery chec)ingabout set,website -http://www !etcode comabout set,logo Gd)::0i7bu" new -battery pngabout run about destroy end end Gt) init window 5 Ruby#pp new Gt) main
3e create an #boutOialog.
about set,program,name -9atteryabout set,Eersion -% Gabout set,copyright -AcD 6an 9odnar-
:D
5igure; 4bout(ialog
FontSelection&ialog
The 8ont2electionOialog is 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: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -8ont2electionOialogsignal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e ;%%/ G.% set,window,position Gt)::+indow::012,C34T3R show,all end de" init,ui set,border,width G% Wlabel 5 Gt)::@abel new -The only Eictory oEer loEe is "light button 5 Gt)::9utton new -2elect "ont-
62
button signal,connect -clic)ed- do on,clic)ed end "i7 "i7 "i7 add end de" on,clic)ed "dia 5 Gt)::8ont2electionOialog new -2elect "ont nameresponse 5 "dia run i" response 55 Gt)::Oialog::R3201423,1K "ont,desc 5 0ango::8ontOescription new "dia "ont,name i" "ont,desc Wlabel modi"y,"ont "ont,desc end end "dia destroy 5 Gt)::8i7ed new put button/ G%%/ ;% put Wlabel/ ;%/ &% "i7
end end
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)::8ont2electionOialog new -2elect "ont name-
If we clic! on the "K button, the font of the label widget changes to the one, that we selected in the dialog.
6/
5igure; 5ont$election(ialog
ColorSelection&ialog
Color2electionOialog #!/usr/bin/ruby # # # # # # # # ZetCode Ruby GTK tutorial This e7ample wor)s with the Color2electionOialog author: jan bodnar website: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -Color2electionOialogsignal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e ;.%/ G.% set,window,position Gt)::+indow::012,C34T3R show,all
60
end de" init,ui set,border,width G% Wlabel 5 Gt)::@abel new -The only Eictory oEer loEe is "light button 5 Gt)::9utton new -2elect colorbutton signal,connect -clic)ed- do on,clic)ed end "i7 "i7 "i7 add end de" on,clic)ed cdia 5 Gt)::Color2electionOialog new -2elect colorresponse 5 cdia run i" response 55 Gt)::Oialog::R3201423,1K colorsel 5 cdia colorsel color 5 colorsel current,color Wlabel modi"y,"g Gt)::2T#T3,41R?#@/ color end end end Gt) init window 5 Ruby#pp new Gt) main cdia destroy 5 Gt)::8i7ed new put button/ G%%/ ;% put Wlabel/ ;%/ &% "i7
The e&le is #ery similar to the pre#ious one. This time we change the color of the label.
cdia 5 Gt)::Color2electionOialog new -2elect color-
If the user pressed "K, we get the color #alue and modify the label>s color.
6:
5igure; Color$election(ialog In this part of the Ruby GTK tutorial, we presented dialogs.
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: www !etcode com last modi"ied: 6une $%%&
66
set,title -Colorssignal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e ;B%/ G%% set,window,position Gt)::+indow::012,C34T3R show,all end de" init,ui Wdarea 5 Gt)::Orawing#rea new Wdarea signal,connect -e7poseKeEent- do on,e7pose end addAWdareaD end de" on,e7pose cr 5 Wdarea window create,cairo,conte7t draw,colors cr end de" draw,colors cr cr set,source,rgb % $/ % $;/ % & cr rectangle G%/ G./ &%/ B% cr "ill cr set,source,rgb % &/ % G/ % G cr rectangle G;%/ G./ &%/ B% cr "ill cr set,source,rgb % C/ % &/ % C cr rectangle $.%/ G./ &%/ B% cr "ill end end
In our e&le, we will draw three rectangles and fill them with three different colors.
Wdarea 5 Gt)::Orawing#rea new
61
end
on,e7pose
3hen the window needs to be redrawn, the the e7poseKeEent is triggered. In response to this e#ent, we call the on,e7pose method.
cr 5 Wdarea window create,cairo,conte7t
3e create the cairo conte&t ob9ect from the Gd)+indow of the drawing area. The conte&t is an ob9ect onto which we do all our drawings.
draw,colors cr
The set,source,rgb method sets a color for the cairo conte&t. The three parameters of the method are the color intensity #alues.
cr rectangle G%/ G./ &%/ 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
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: www !etcode com last modi"ied: 6une $%%&
6A
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -9asic shapessignal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e ;&%/ $C% set,window,position Gt)::+indow::012,C34T3R end show,all
de" init,ui Wdarea 5 Gt)::Orawing#rea new Wdarea signal,connect -e7poseKeEent- do on,e7pose end addAWdareaD end de" on,e7pose cr 5 Wdarea window create,cairo,conte7t draw,shapes cr end de" draw,shapes cr cr set,source,rgb % B/ % B/ % B cr rectangle $%/ $%/ G$%/ :% cr rectangle G:%/ $%/ :%/ :% cr "ill cr arc ;;%/ B%/ C%/ %/ $J?ath::0> cr "ill cr arc &%/ GB%/ C%/ ?ath::0>/C/ ?ath::0> cr "ill cr cr cr cr end end translate $$%/ G:% scale G/ % H arc %/ %/ .%/ %/ $J?ath::0> "ill
6B
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.
cr rectangle $%/ $%/ G$%/ :% cr rectangle G:%/ $%/ :%/ :% cr "ill
The translate method mo#es the ob9ect to a specific point. If we want to draw an o#al, we do some scaling first. -ere the scale method shrin!s the y a&is.
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@
6C
#!/usr/bin/ruby # # # # # # # # ZetCode Ruby GTK tutorial This program shows transparent rectangles using Cairo author: jan bodnar website: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -Transparent rectanglessignal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e .&%/ &% set,window,position Gt)::+indow::012,C34T3R show,all end de" init,ui Wdarea 5 Gt)::Orawing#rea new Wdarea signal,connect -e7poseKeEent- do on,e7pose end addAWdareaD end de" on,e7pose cr 5 Wdarea window create,cairo,conte7t "or i in AG G%D cr set,source,rgba %/ %/ G/ iJ% G cr rectangle .%Ji/ $%/ C%/ C% cr "ill end
end end
In the e&le we will draw ten rectangles with different le#els of transparency. 6D
cr set,source,rgba %/ %/ G/ iJ% G
&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: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -Oonutsignal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e ;.%/ $.% set,window,position Gt)::+indow::012,C34T3R end show,all
de" init,ui Wdarea 5 Gt)::Orawing#rea new Wdarea signal,connect -e7poseKeEent- do on,e7pose end addAWdareaD
12
end de" on,e7pose cr 5 Wdarea window create,cairo,conte7t cr set,line,width % . w 5 allocation width h 5 allocation height cr translate w/$/ h/$ cr arc %/ %/ G$%/ %/ $J?ath::0> cr stro)e "or i in AG ;BD cr saEe cr rotate iJ?ath::0>/;B cr scale % ;/ G cr arc %/ %/ G$%/ %/ $J?ath::0> cr restore cr stro)e end
end end
In this e&le, we create a donut. The shape resembles a coo!ie, hence the name donut.
cr translate w/$/ h/$ cr arc %/ %/ G$%/ %/ $J?ath::0> cr stro)e
1/
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: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( class Ruby#pp * Gt)::+indow de" initiali!e super set,title -2oulmatesignal,connect -destroy- do Gt) main,'uit end init,ui set,de"ault,si!e ;H%/ $C% set,window,position Gt)::+indow::012,C34T3R show,all end de" init,ui Wdarea 5 Gt)::Orawing#rea new
10
Wdarea signal,connect -e7poseKeEent- do on,e7pose end addAWdareaD end de" on,e7pose cr 5 Wdarea window create,cairo,conte7t cr set,source,rgb % G/ % G/ % G cr select,"ont,"ace -0urisa-/ Cairo::814T,2@#4T,41R?#@/ Cairo::814T,+3>GIT,41R?#@ cr set,"ont,si!e G; cr cr cr cr cr cr cr cr cr cr cr cr moEe,to $%/ ;% show,te7t -?ost relationships seem so transitorymoEe,to $%/ B% show,te7t -They(re all good but not the permanent onemoEe,to $%/ G$% show,te7t -+ho doesn(t long "or someone to holdmoEe,to $%/ G.% show,te7t -+ho )nows how to loEe without being toldmoEe,to $%/ G:% show,te7t -2omebody tell me why >(m on my ownmoEe,to $%/ $G% show,te7t ->" there(s a soulmate "or eEeryone-
end end
3e display part of the lyrics from the .atasha 'edingfields $oulmate song.
cr select,"ont,"ace -0urisa-/ Cairo::814T,2@#4T,41R?#@/ Cairo::814T,+3>GIT,41R?#@
1:
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: !etcode com last edited: 6une $%%&
re'uire (gt)$( class 9urning * Gt)::Orawing#rea de" initiali!eAparentD Wparent 5 parent superAD
16
Wnum 5 X -H.-/ -G.%-/ -$$.-/ -;%%-/ -;H.-/ -C.%-/ -.$.-/ -B%%-/ -BH.- Y set,si!e,re'uest G/ ;% signal,connect -e7poseKeEent- do e7pose end end de" e7pose cr 5 window create,cairo,conte7t draw,widget cr end de" draw,widget cr cr set,line,width % : cr select,"ont,"aceA-Courier-/ Cairo::814T,2@#4T,41R?#@/ Cairo::814T,+3>GIT,41R?#@D cr set,"ont,si!e GG width 5 allocation width Wcur,width 5 Wparent get,cur,Ealue step 5 Awidth / G% %D round till 5 Awidth / H.% %D J Wcur,width "ull 5 Awidth / H.% %D J H%% i" Wcur,width F5 H%% cr cr cr cr cr cr cr cr cr cr else cr cr cr cr cr set,source,rgb G %/ G %/ % H$ rectangle %/ %/ till/ ;% clip paint reset,clip set,source,rgbAG %/ G %/ % H$D rectangleA%/ %/ "ull/ ;%D clip paint reset,clip set,source,rgbAG %/ % B:/ % B:D rectangleA"ull/ %/ tillK"ull/ ;%D clip paint reset,clip
end
11
cr moEe,to iJstep/ % cr line,to iJstep/ . cr stro)e te cr cr cr end end class Ruby#pp * Gt)::+indow de" initiali!e super set,title -9urningsignal,connect -destroy- do Gt) main,'uit end set,si!e,re'uest ;.%/ $%% set,window,position Gt)::+indow::012,C34T3R Wcur,Ealue 5 % Ebo7 5 Gt)::=9o7 new "alse/ $ scale scale scale scale scale 5 Gt)::I2cale new set,range %/ H.% set,digits % set,si!e,re'uest GB%/ ;. set,Ealue Wcur,Ealue end 5 cr te7t,e7tents WnumXiKGY moEe,to iJstepKte width/$/ G. te7t,path WnumXiKGY stro)e
scale signal,connect -EalueKchanged- do MwM on,changedAwD end "i7 5 Gt)::8i7ed new "i7 put scale/ .%/ .% Ebo7 pac),start "i7 Wburning 5 9urning newAsel"D Ebo7 pac),start Wburning/ "alse/ "alse/ % add Ebo7 show,all
end
end
1A
3e put a Orawing#rea on the bottom of the window and draw the entire widget manually. 4ll the important code resides in the draw,widget which is called from the e7pose method 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.-/ -G.%-/ -$$.-/ -;%%-/ -;H.-/ -C.%-/ -.$.-/ -B%%-/ -BH.- Y
These numbers are shown on the burning widget. They show the capacity of the medium.
Wcur,width 5 Wparent get,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 till parameter determines the total si8e to be drawn. This #alue comes from the slider widget. It is a proportion of the whole area. The "ull parameter determines the point, where we begin to draw in red color.
cr cr cr cr cr set,source,rgbAG %/ G %/ % H$D rectangleA%/ %/ "ull/ ;%D clip paint reset,clip
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 widget Ealue Wburning 'ueue,draw end
3e get the #alue from the scale widget, store it in the Wcur,Ealue #ariable for later use. 3e redraw the burning widget. 1B
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. "ibbles is 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. <ach time the sna!e eats an apple, its body grows. The sna!e must a#oid the walls and its own body.
&e'elopment
The si8e of each of the 9oints of a sna!e is /2p&. The sna!e is controlled with the cursor !eys. Initially, the sna!e has three 9oints. The game starts immediately. 3hen the game is finished, we display GGame "#erG message in the center of the window. board.rb
+>OTI 5 ;%% I3>GIT 5 $H% O1T,2>Z3 5 G% #@@,O1T2 5 +>OTI J I3>GIT / AO1T,2>Z3 J O1T,2>Z3D R#4O,012 5 $B Q7 5 X%Y J #@@,O1T2 Qy 5 X%Y J #@@,O1T2 class 9oard * Gt)::Orawing#rea de" initiali!e super modi"y,bg Gt)::2T#T3,41R?#@/ Gd)::Color newA%/ %/ %D signal,connect -e7poseKeEent- do on,e7pose end
1C
end
init,game
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 .% K i J G% QyXiY 5 .% end begin Wdot 5 Cairo::>mage2ur"ace "rom,png -dot pngWhead 5 Cairo::>mage2ur"ace "rom,png -head pngWapple 5 Cairo::>mage2ur"ace "rom,png -apple pngrescue 37ception 5F e puts -cannot load imagese7it end locate,apple G@ib::Timeout addAG%%D S on,timer U end de" on,e7pose cr 5 window create,cairo,conte7t i" WinGame draw,objects cr else game,oEer cr end end de" draw,objects cr cr set,source,rgb %/ %/ % cr paint
1D
cr set,source Wapple/ Wapple,7/ Wapple,y cr paint "or ! in A% WdotsD i" ! 55 % cr set,source Whead/ Q7X!Y/ QyX!Y cr paint else cr set,source Wdot/ Q7X!Y/ QyX!Y cr paint end end end de" game,oEer cr w 5 allocation width / $ h 5 allocation height / $ cr set,"ont,si!e G. te 5 cr te7t,e7tents -Game 1Eercr set,source,rgb B..;./ B..;./ B..;. cr moEe,to w K te width/$/ h cr show,te7t -Game 1Eerend de" chec),apple i" Q7X%Y 55 Wapple,7 and QyX%Y 55 Wapple,y Wdots 5 Wdots L G locate,apple end end de" moEe ! 5 Wdots while ! F Q7X!Y QyX!Y ! 5 ! end % 5 Q7XA! K GDY 5 QyXA! K GDY K G
i" Wle"t Q7X%Y K5 O1T,2>Z3 end i" Wright Q7X%Y L5 O1T,2>Z3 end i" Wup QyX%Y K5 O1T,2>Z3 end i" Wdown
A2
end end
QyX%Y L5 O1T,2>Z3
de" chec),collision ! 5 Wdots while ! F % i" ! F C and Q7X%Y 55 Q7X!Y and QyX%Y 55 QyX!Y WinGame 5 "alse end ! 5 ! K G end i" QyX%Y F I3>GIT K O1T,2>Z3 WinGame 5 "alse end i" QyX%Y * % WinGame 5 "alse end i" Q7X%Y F +>OTI K O1T,2>Z3 WinGame 5 "alse end i" Q7X%Y * % WinGame 5 "alse end end de" locate,apple r 5 randAR#4O,012D Wapple,7 5 r J O1T,2>Z3 r 5 randAR#4O,012D Wapple,y 5 r J O1T,2>Z3 end de" on,)ey,down eEent )ey 5 eEent )eyEal i" )ey 55 Wle"t Wup 5 Wdown end Gd)::KeyEal::GOK,@e"t and not Wright 5 true "alse 5 "alse
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/
end
Wle"t 5 "alse
i" )ey 55 Gd)::KeyEal::GOK,Oown and not Wup Wdown 5 true Wright 5 "alse Wle"t 5 "alse end end end
5irst we will define some globals used in our game. The 3I(T- and -<IG-T constants determine the si8e of the 'oard. The ("TH$II< is the si8e of the apple and the dot of the sna!e. The 4%%H("T$ constant defines the ma&imum number of possible dots on the 'oard. The R4.(H "$ constant is used to calculate a random position of an apple. The (<%4J constant determines the speed of the game.
Q7 5 X%Y J #@@,O1T2 Qy 5 X%Y J #@@,O1T2
These two arrays store &, y coordinates of all possible 9oints of a sna!e. The init,game method initiali8es #ariables, loads images and starts a timeout function.
i" WinGame draw,objects cr else game,oEer cr end
Inside the on,e7pose method, we chec! the WinGame #ariable. If it is true, we draw our ob9ects. The apple and the sna!e 9oints. "therwise we display GGame o#erG te&t.
de" draw,objects cr cr set,source,rgb %/ %/ % cr paint cr set,source Wapple/ Wapple,7/ Wapple,y cr paint "or ! in A% WdotsD i" ! 55 % cr set,source Whead/ Q7X!Y/ QyX!Y cr paint else cr set,source Wdot/ Q7X!Y/ QyX!Y cr paint end end end
The draw,objects method draws the apple and the 9oints of the sna!e. The first 9oint of a sna!e is its head, which is represented by a red circle.
A0
de" chec),apple i" Q7X%Y 55 Wapple,7 and QyX%Y 55 Wapple,y Wdots 5 Wdots L G locate,apple end end
The chec),apple method chec!s, if the sna!e has hit the apple ob9ect. If so, we add another sna!e 9oint and call the locate,apple method, which randomly places a new apple ob9ect. In the moEe method 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 Q7X!Y QyX!Y ! 5 ! end % 5 Q7XA! K GDY 5 QyXA! K GDY K G
Mo#e the head to the left. In the chec),collision method, we determine if the sna!e has hit itself or one of the walls.
while ! F % i" ! F C and Q7X%Y 55 Q7X!Y and QyX%Y 55 QyX!Y WinGame 5 "alse end ! 5 ! K G end
5inish the game, if the sna!e hits one of its 9oints with the head.
i" QyX%Y F I3>GIT K O1T,2>Z3 WinGame 5 "alse end
5inish the game, if the sna!e hits the bottom of the 'oard. The locate,apple method locates an apple randomly on the board.
r 5 randAR#4O,012D
A:
Wapple,y 5 r J O1T,2>Z3
<#ery /62 ms, the on,timer method is called. If we are in the game, we call three methods, that build the logic of the game. "therwise we return "alse, which stops the timer e#ent. In the on,)ey,down method of the 'oard class, we determine the !eys that were pressed.
i" )ey 55 Wle"t Wup 5 Wdown end Gd)::KeyEal::GOK,@e"t and not Wright 5 true "alse 5 "alse
If we hit the left cursor !ey, we set le"t #ariable to true. This #ariable is used in the moEe method to change coordinates of the sna!e ob9ect. .otice also, that when the sna!e is heading to the right, we cannot turn immediately to the left. nibbles.rb
# # # # # # # # #!/usr/bin/ruby ZetCode Ruby GTK tutorial This is a simple nibbles game clone author: jan bodnar website: www !etcode com last modi"ied: 6une $%%&
re'uire (gt)$( re'uire (board( class Ruby#pp F Gt)::+indow de" initiali!e super set,title -4ibblessignal,connect -destroy- do Gt) main,'uit end Wboard 5 9oard new signal,connect -)eyKpressKeEent- do Mw/ eM on,)ey,downAw/ eD end
A6
add Wboard set,de"ault,si!e ;%%/ $H% set,window,position Gt)::+indow::012,C34T3R show,all end de" on,)ey,down widget/ eEent )ey 5 eEent )eyEal Wboard on,)ey,down eEent end end
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 This was the .ibbles computer game programmed with the GTK library and the Ruby programming language.
A1