This Article covers the use of the Python Tkinter List box, its parameters, and common events associated with the list box.
What is the Python Tkinter List Box?
A Python Tkinter widget that is used to display a list of options for the user to select. A List Box displays all of its options at once, unlike the ComboBox for instance. Furthermore, all options are in text format.
listbox = Listbox(root, arguments........) List Box Arguments
| No. | Option | Description |
|---|---|---|
| 1 | bg | Background color for the area around the widget. |
| 2 | bd | Size of the border around the widget. Default value is 2 pixels. |
| 3 | cursor | When the mouse is hovering over this widget, it can be changed to a special cursor type like an arrow or dot. |
| 4 | font | The type of font to be used for this widget. |
| 5 | fg | The color for the text. |
| 6 | height | Number of lines displayed in the List box. Defaut value is 10. |
| 7 | highlightcolor | The text color when the widget is under focus. |
| 8 | relief | It specifies the type of the border. Default is Flat, other options include RAISED and SUNKEN. |
| 9 | selectbackground | Background color for text that has been selected. |
| 10 | selectmode | It determines the number of items that can be selected from the list and the effects of the mouse on this selection. It can set to BROWSE, SINGLE, MULTIPLE, EXTENDED. |
| 11 | width | The width of the widget in characters. |
| 12 | xscrollcommand | Allows the user to scroll horizontally. |
| 13 | yscrollcommand | Allows the user to scroll vertically. |
List Box Example 1
Below is a demonstration on how to create a Tkinter List box in Python. It’s syntax is relatively simple. Only the List box object needs to be created and you can keep adding items into it using the insert function.
Python
from tkinter import *
root = Tk()
root.geometry("200x220")
frame = Frame(root)
frame.pack()
label = Label(root,text = "A list of Grocery items.")
label.pack()
listbox = Listbox(root)
listbox.insert(1,"Bread")
listbox.insert(2, "Milk")
listbox.insert(3, "Meat")
listbox.insert(4, "Cheese")
listbox.insert(5, "Vegetables")
listbox.pack()
root.mainloop()