Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Tkinter Listbox and Option Menu – How to Use the Listbox and Option Menu Widgets?

Tkinter Listbox And Option Menu

Hey guys, welcome to this article on Tkinter Listbox and Option menu using Tkinter. I will walk you through some examples for the same.

What is a Listbox?

The Listbox widget in Tkinter is widely used to display a set of items to the user. The user can select from these items.

We have the basic starter code that we always get, a 400 x 400 and we have got an icon for the title in there.

from tkinter import *

root=Tk()
root.title("Listbox demo")
root.geometry("400x480")

root.mainloop()

So to create a list box, you just define it like always and a list box is just a type of widget with tkinter.

Create your first Tkinter listbox widget

Let’s create a list box, we’ll call it my_listbox and set that equal to a Listbox() and put it in root.

We will pack this on the screen and let’s give this a pack() and give it a “pady” of 15.

#Listbox
my_listbox=Listbox(root)
my_listbox.pack(pady=15)

Adding items to the listbox individually

Now, in order to put things in, you could do it in a couple of different ways. You can just do it manually or you could create a list and loop through the list and put each of those things in it one at a time.

We will be using my_listbox.insert method. This method takes two parameters. There’s an index and a string.

So the index is the index number, the item in our list box, the position in which we want to put it in and the first one is ‘0’.

# Add item to listbox

my_listbox.insert(END, "First")  
my_listbox.insert(END, "Second")

Adding mutliple items to a Tkinter listbox using loops

Let’s add a list of items. So I’m going to just create my_list and it’s just going to be a python list and we can put anything we want in here. So I’m just going to insert “one”, “two” and “three” and that’s fine. Now we can just loop through the list and put each item in there.

my_list = ["One", "Two", "Three"]

for item in my_list:
	my_listbox.insert(END, item)

Adding Tkinter Buttons to Delete Listbox Items

Now that we know how to add listbox items, let’s create a Tkinter button to delete the items.

If we click on one of these items they get highlighted, so let’s create a button. We will call it my_button and that’s going to be in root and pack my_button with a pady of 10.

my_button = Button(root, text="Delete", command=delete)     
my_button.pack(pady=10)

Now, we need to create a delete function. When something is highlighted in your list box after you’ve clicked on it, it becomes the anchor. So, we want to delete the ANCHOR.

def delete():
    my_listbox.delete(ANCHOR)
    my_label.config(text=" ")

The complete code for Tkinter Listbox widget implementation

from tkinter import *

root=Tk()
root.title("Listbox demo")
root.geometry("400x480")

#Listbox
my_listbox=Listbox(root)
my_listbox.pack(pady=15)

# Add item to listbox

my_listbox.insert(END, "First")  
my_listbox.insert(END, "Second")

my_list = ["One", "Two", "Three"]

for item in my_list:
    my_listbox.insert(END, item)

def delete():
    my_listbox.delete(ANCHOR)
    my_label.config(text=" ")

my_button = Button(root, text="Delete", command=delete)     
my_button.pack(pady=10)

global my_label

my_label=Label(root, text=" ")
my_label.pack(pady=5)

root.mainloop()

The output of the above code is as shown below:

List Item
List Item

What is an Option menu?

The OptionMenu class is a helper class that creates a popup menu, and a button to display it. This widget generates a drop down list with many option values.

Let’s create a simple Option Menu structure.

Create your first Tkinter Option menu

To create an options menu based on the dropdown menu. The first step for this is to list out Basic security questions. Pass them into an options menu and create an entry for an answer.

First, we will create list of questions.

Question = [“What is your mother’s maiden name?”,
                    “ Who is your favorite author?”,
                    “ What was your first pets name? “,
                     “What street did you grow up on? “
] 

Now we have to pass these through a variable tkvarq. To understand creation of tk variable, the first alternate to pass barrier is root and set the questions for this variable using the set().

This is a string variable StringVar , we pass the questions into it as shown below:

tkvarq = StringVar(root) 
tkvarq.set(questions[0])

Creating the Tkinter OptionMenu object

The questions are displayed by creating an object of OptionMenu and the answers can be entered on the answer_entry text box created. This text box has been created using the Entry class.

question_menu = OptionMenu(root,  tkvarq, *questions)
question_menu.pack()

#Answer entry
answer_entry = Entry(root, width=30)
answer_entry.pack()

The complete code for Tkinter OptionMenu widget implementation

from tkinter import *
root = Tk()
root.title(“Option Menu”)
root.geometry(‘700x500’)

# Create the list of questions
# Pass them into an option menu
# Create an entry for the answer
# Create submit button

def print_answers():
       print (“Q: {}    A:  {} “,format(tkvarq.get(),  answer_entry.get()))
       return None 

Question = [“What is your mother’s maiden name?”,
                    “ Who is your favorite author?”,
                    “ What was your first pets name? “,
                     “What street did you grow up on? “
] 

tkvarq = StringVar(root) 
tkvarq.set(questions[0])
question_menu = OptionMenu(root,  tkvarq, *questions)
question_menu.pack()

#Answer entry
answer_entry = Entry(root, width=30)
answer_entry.pack()

#Submit button
submit_button = Button(root, test=’Submit’,  command=print_answers)
submit_button.pack()

root.mainloop()

This code generates an options menu which contains the questions. You can choose one question that you wish to answer and write your answer for it in the text box provided.

Kindly note, this code does not contain the validations, meaning it will not tell you if the answer entered is correct or not.

The output of the above code is as shown below:

Option Menu
Option Menu

Conclusion

This comes to the end of our tutorial on the Tkinter Listbox and option menu. Do try out the examples shown and give your feedback in the comment section below.