|
The last lines pack the root frame and then we enter the main GUI event loop.
You can pass options to a widget in a Hash or you can pass options using a code block.Widgets take the parent as first argument, followed by a hash or code block of options.
In our examples, padx and pady are distances in pixels by default.You can use other units by specifying one of the suffixes c for centimeters, i for inches, m for millimeters, or p for points.
How to get information back from widgets
By setting up callbacks and by binding variables.
[edit] Ruby Callbacks
Let's assume you want to create an exit button for your application.
require 'tk'
TkButton.new do
text 'Exit'
command { exit }
pack(’side’=>’left’, ‘padx’=>15, ‘pady’=>15)
end
Tk.mainloop
You've probably already started to realize by now that an application GUI is made by staking several widgets together...
The code block in the command method is run when the user clicks the button."Command" takes a Proc object.
[edit] Binding Ruby events
How to capture events such as mouse over mov, cliks and so on?
Create a binding from an event on a widget to a code block using the bind method.
Think of some nice rollover effects on a menu:
require 'tk'
image1 = TkPhotoImage.new { file "button1.gif" }
image2 = TkPhotoImage.new { file "button2.gif" }
btn = TkButton.new(@root) do
image buttonimg1
command { exit }
pack
end
btn.bind("Enter") { btn.configure('image'=>buttonimg2) }
btn.bind("Leave") { btn.configure('image'=>buttonimg1) }
Tk.mainloop
Using TkPhotoImage, 2 image objects are created from already existent gif files.A button called btn is created and will display the image1 image.
We then use 2 binds on "enter" and "leave" that will change the displayed image accordingly...much like a classic rollover would work.
[edit] Ruby Scrolling
When implementing scrollbars you need to keep in mind that they're in close relationship with widgets.When a scrollbar moves it means that a widget's view needs to change also, or when a widget's view is modified by external means, a scrollbar should move too in order to reflect the change.
Here's an example of code from another very useful Ruby/Tk tutorial here
root = TkRoot.new() { title "(Sc)rolling, (sc)rolling), (sc)rolling..." }
bar = TkScrollbar.new(root, 'orient'=>'hor').pack('side'=>'bottom', 'fill'=>'x')
text = TkText.new(root, 'wrap'=>'none', 'width'=>20).pack('fill'=>'both', 'expand'=>true)
text.insert('end', "A string that is longer than fits on one line...")
bar.command(proc { |args|
text.xview(*args)
})
text.xscrollcommand(proc { |first, last|
bar.set(first, last)
})
|