Python Tkinter Dropdown Menu

This tutorial will show how to create a Dropdown menu feature using the Tkinter Library. The Tkinter library is used to create GUIs and various different elements and Dialog Windows.

To create a dropdown menu the Tkinter widget OptionMenu will be used.

This program will use an OptionMenu to let user selected size. If the “Print ” button is clicked it will print out the selected Size. When the user selects a size, the selected sizes will be given a 1 and the unselected sizes a 0

from tkinter import *

SIZES = ['Small','Med.','Large','XL']

#Get Selected Sizes
def print_SIZES(*args):
   values = [(Size, var.get()) for Size, var in data.items()]
   values
   print(values)

data = {} # dictionary to store all the IntVars

#tkinter option menu
TKINTER = Tk()
TKINTER.title("Size Selector")
bMenu=  Menubutton ( TKINTER, text="Select Size ", relief=RAISED )
bMenu.menu  =  Menu ( bMenu, tearoff = 0 )
bMenu["menu"]  =  bMenu.menu

#if selected 
for Size in SIZES:
    var = IntVar()
    bMenu.menu.add_checkbutton(label=Size, variable=var)
    data[Size] = var # add IntVar to the dictionary

btn = Button(TKINTER, text="Print", command=print_SIZES)

btn.pack()
bMenu.pack()
TKINTER.mainloop()

Output:

[('Small', 0), ('Med.', 1), ('Large', 1), ('XL', 0)]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s