# Binding or executing a command with a TkOptionMenubutton

**URL:** <https://www.ruby-forum.com/t/binding-or-executing-a-command-with-a-tkoptionmenubutton/89009>\
**Category:** Ruby\
**Created:** [March 16, 2007, 2:13pm UTC](https://www.ruby-forum.com/t/binding-or-executing-a-command-with-a-tkoptionmenubutton/89009 "2007-03-16T14:13:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![alexd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/96bed5/32.png) [@alexd](https://www.ruby-forum.com/u/alexd)\
**Post date:** [March 16, 2007, 2:13pm UTC](https://www.ruby-forum.com/t/binding-or-executing-a-command-with-a-tkoptionmenubutton/89009/1 "2007-03-16T14:13:20Z")

</div>

I want my program to execute a command whenever a new selection is made  
from a TkOptionMenubutton. The -command option isn’t allowed with  
TkOptionMenubuttons, so I’ve been experimenting with various bindings,  
but can’t find an appropriate binding event.

I’ve tried the following simple example which should print the value of  
the selection, but it only works if the mouse is directly over the  
button itself, and not over the expanded options.

Any ideas how to do this?

#------------------------------------  
require ‘tk’  
root = TkRoot.new.title(“MenuOptionbutton”)

list = [“1”, “2”, “3”, “4”, “5”]  
var = TkVariable.new  
button = TkOptionMenubutton.new(root,var,\*list).pack  
button.bind(‘ButtonRelease-1’) do  
print var, “\n”  
end

Tk.mainloop

#--------------------------------------------

---

<div class="post-metadata">

**Author:** ![alexd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/96bed5/32.png) [@alexd](https://www.ruby-forum.com/u/alexd)\
**Post date:** [March 16, 2007, 3:10pm UTC](https://www.ruby-forum.com/t/binding-or-executing-a-command-with-a-tkoptionmenubutton/89009/2 "2007-03-16T15:10:33Z")

</div>

From: Alex DeCaria [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
Subject: Binding or executing a command with a TkOptionMenubutton  
Date: Fri, 16 Mar 2007 22:13:22 +0900  
Message-ID: [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)

> I’ve tried the following simple example which should print the value of  
> the selection, but it only works if the mouse is directly over the  
> button itself, and not over the expanded options.
> 
> Any ideas how to do this?

## For example,

require ‘tk’  
root = TkRoot.new.title(“MenuOptionbutton”)

list = [“1”, “2”, “3”, “4”, “5”]  
var = TkVariable.new  
button = TkOptionMenubutton.new(root,var,\*list).pack  
menu = button.menu  
menu.bind(‘ButtonRelease-1’, ‘@%y’){|y|  
value = menu.entrycget(y, :value)  
print var, ’ → ', value, “\n”  
}

# OR,

#menu.bind(‘ButtonRelease-1’, ‘%y’){|y|

# value = menu.entrycget(“@#{y}”, :value)

# print var, ’ → ', value, “\n”

#}

Tk.mainloop
