Tk - Menu Widget


Advertisements

Tk menu widget is used along with Tk widget menubutton. So, we will see menubutton first. The syntax for menu button widget is shown below −

menubutton menubuttonName options

Menu Button Options

The options available for the menu button widget are listed below in the following table −

Sr.No. Syntax & Description
1

-command action

Sets the command action for button.

2

-text text

Sets the text for the widget.

3

-textvariable varName

Variable associated with the widget. When the text of widget changes, the variable is set to text of widget.

4

-width number

Sets the width for widget.

5

-menu menuName

Specifies the name of associated menu widget.

6

-underline charPosition

Sets the position for hotkey.

The syntax for menu is shown below −

menu menuName options

Menu Options

The options available for the menu widget are listed below in the following table −

Sr.No. Syntax & Description
1

-font fontDescriptor

Used to set font for widget.

2

-postcommand action

Sets the command action to be done before a menu is posted.

3

-menu menuName

Specifies the name of associated menu widget.

4

-tearoff boolean

Allows or disallows a menu to be removed from the menubutton and displayed in a permanent window. Default is enabled.

The syntax for adding menubutton is shown below −

menuName add type menubuttonType options

The type includes separator, cascade, checkbutton, radiobutton, and command.

MenuName Add Options

The options available for the menuName add are listed below in table −

Sr.No. Syntax & Description
1

-command action

Sets the command action for the menubutton.

2

-menu menuName

Specifies the name of associated menu widget.

3

-label string

Set the text of the menu.

4

-variable varName

Sets the variable to be set when this entry is selected.

5

-value string

The value is set for the variable.

6

-underline position

Sets the position for hotkey.

A simple Tk menu is shown below −

#!/usr/bin/wish

menubutton .myMenubutton -menu .myMenubutton.myMenu -text "ChangeText"
menu .myMenubutton.myMenu
.myMenubutton.myMenu add command -label Hello -command {set myvariable "Hello"}
.myMenubutton.myMenu add command -label World -command {set myvariable "World"}
pack .myMenubutton
pack [label .myLabel  -text "Select An option" -font {Helvetica -18 bold} -height 5
   -width 15 -textvariable myvariable]

When we run the above program, we will get the following output −

Menu Example

When we select a menu option, we will get an output as shown below −

Menu Example Selected
tk_selection_widgets.htm
Advertisements