| Hello, World! | Simple Widgets | Binding Events | More Widgets | Scrollbars | Menus | Canvas | Make things look Beautiful | More Information |
| We are moving to this wiki |
|---|
Beware that menus in itself are complex widgets. A bar with a menu that shows options and submenus when you click on it, each of them bound to a command, possibly hooked to a key-sequence as well, is a bit more than just a button. But its the menu that's complex, not the implementation.
root = TkRoot.new() { title "Ruby/Tk Menu Example" }
bar = TkMenu.new()
sys = TkMenu.new(bar)
sys.add('command', 'label'=>"Quit", 'command'=>proc { root.destroy })
bar.add('cascade', 'menu'=>sys, 'label'=>"System")
file = TkMenu.new(bar)
file.add('command', 'label'=>"Open", 'command'=>proc { puts "Open..." })
file.add('command', 'label'=>"Close", 'command'=>proc { puts "Close..." })
bar.add('cascade', 'menu'=>file, 'label'=>"File")
root.menu(bar)
What happened?
Other types of menus exist as well, the entire list is: command, separator, cascade (submenu), checkbutton and radiobutton.
I think the implementation should be changed, because the idea is good. Typically, you would write a way of building menus like this if you need many menus.
It works like this:
menu_spec = [
[ ['File', 0],
['New File', proc{new_file}],
['Open File', proc{open_file}],
'---',
['Save File', proc{save_file}],
['Save As', proc{save_as}],
'---',
['Quit', proc{exit}]
],
[ ['Edit', 0],
['Cut', proc{cut_text}],
['Copy', proc{copy_text}],
['Paste', proc{paste_text}]
]
]
TkMenubar.new(nil, menu_spec, 'tearoff'=>false).pack('fill'=>'x', 'side'=>'top')
Note: Tk does not know a separate class menubar, it's just a plain toplevel menu.
root = TkRoot.new() { title "Example Menu Event" }
names = ["One", "Two", "Three"]
var = TkVariable.new()
button = TkOptionMenubutton.new(root, var, *names)
button.pack
Tk passes a virtual event <<MenuSelect>> to the menu
when some activation is made. Since the Tk bindings pre-/append `<' and
`>' already, we need to catch the event like this:
button.menu.bind("<MenuSelect>") { p "Menu select!!! (#{var})" }
Note that activation is not only the selection of a new value, but also each
change of highlighting while you are selecting a new value.
some_widget.bind("Button-3") { |evt| menu.popup(x_root, y_root) }
where we use x_root and y_root because a popup menu is in fact a toplevel
window that ignores the window manager. So we need to tell it the exact (x, y)
w.r.t. the root window. menu is a TkMenu, like bar in the
topmost example.
| Hello, World! | Simple Widgets | Binding Events | More Widgets | Scrollbars | Menus | Canvas | Make things look Beautiful | More Information |