Python Listbox - How do i make Listbox Tkinter

Published December 12, 2021

The Tkinter Listbox is used to display a list of various items to the application user. In the list boxes, items of the same font and color are displayed, and the user can make single or multiple selections depending on the provided configuration.

 

How Tkinter Listbox works

To create a Tkinter Listbox, you should follow the syntax below, where the parent represents the window, and the options represent the list of various attributes used for the widgets.

w = Listbox(parent, options)

The Tkinter ListBox Options

  • Bg: specifies the background color of the listbox

  • Bd: indicates the border size. The default value is 2 px.

  • Cursor: specifies the appearance of the mouse pointer when it hovers over the widget.

  • Font: specifies the font family of the list elements.

  • Fg: specifies the font color.

  • Height: specifies the number of lines in a Listbox.

  • Highlightcolor: specifies the color of the list items under focus.

  • Highlighthickness: specifies the thickness of the list items under focus

  • Relief: determines the kind of border utilized

  • Selectbackground: shows the background color of the chosen text.

  • Selectmode: specifies the number of the items picked in a list

  • Yscrollcommand: scrolls the list elements vertically.

  • Xscrollcommand: scrolls the list elements horizontally.

  • Width: specifies the span of the list items in terms of the characters.

 

Examples of Tkinter Listbox

Example: List of programming Languages

The following is an example of a lisbox displaying four programming languages:

 

from tkinter import *

top = Tk()

top.geometry("200x250")

lbl = Label(top, text="A list of programming languages", bg="red", bd="3px")

listbox = Listbox(top)

listbox.insert(1, "Python")

listbox.insert(2, "C++")

listbox.insert(3, "C#")

listbox.insert(4, "Java")

lbl.pack()

listbox.pack()

top.mainloop()

 

 

If you execute the above code, you will see the following output on your screen.

Python Listbox How do i make tikinter listbox

 

 

Example 2:  Deletes  the selected List Item

In this example, we have added a button that will allow you to delete the selected programming language

from tkinter import *

top = Tk()

top.geometry("400x350")

lbl = Label(top, text="A list of best Programming Languages")

listbox = Listbox(top)

listbox.insert(1, "Python")

listbox.insert(2, "C++")

listbox.insert(3, "PHP")

listbox.insert(4, "Bootstrap")

# this button will delete the selected programming language from the list

btn = Button(top, text="delete", command=lambda listbox=listbox: listbox.delete(ANCHOR))

lbl.pack()

listbox.pack()

btn.pack()

top.mainloop()

 

 

Python Tkinter Listbox example

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

931 Views