Tkinter - Listbox in Python


Listbox

This is a simple example of a listbox (list box) using tkinter and python.
#import Tkinter
import tkinter

def printVariable(event=0):
    #This function prints the option selected
    if len(ltbox.curselection()) == 0:
        print ("Nothing Selected")
    else:
        print ("Option " + str(ltbox.curselection()[0]+1))
    

#create a window
window = tkinter.Tk()

#Sets window title
window.title("ListBox Example")

#Create a Label
lbldoctype = tkinter.Label(window, text="   Option Choice:    ")
lbldoctype.pack()

#Create the listbox
ltbox = tkinter.Listbox(window)
#Insert data in listbox
ltbox.insert( 1, "Option 1")
ltbox.insert( 2, "Option 2")
ltbox.insert( 3, "Option 3")
ltbox.insert( 4, "Option 4")
#Pack the combobox
ltbox.pack()


#create a button widget called btn
btn = tkinter.Button(window, text="     Select     ", command=printVariable)
#pack the button into the window
btn.pack()

#Return / Enter runs the fucntion the same as clicking the button
window.bind('<Return>', printVariable)

#Loops the tkinter window
window.mainloop()
Creates this window:

When an item is selected this is printed

Option 2






Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.
Tkinter - Learn the key features of the tkinter to allow you to create user interfaces for your python programs.


Must Read Articles

Tkinter - Combo Box - This is a short example showing how to use combo boxes in a GUI.
Tkinter - Radio Buttons - A short example of how to create a GUI with radio buttons.
Tkinter _ Canvas - Canvas allows for a range of shapes to be plotted, such as circles, squares, lines and labels.
Tkinter - Pack vs Grid vs Place - tkinter provides flexibility in how the layout the widgets. 
Pickle - The pickle library allows a program to save data in a binary file.
Python - List Comprehension - Create powerful list comprehension expressions.
Python - Generators - Learn about generator statements.
Python - Data types - The learn about the key datatypes in the python language.