LISTBOX IN TKINTER
In this tutorial, we are going to learn about listbox in Tkinter along with its features and methods followed by a working example.
What is Listbox in Tkinter?
The Listbox widget in Tkinter is used to provide multiple options confined as a list. The List can only contain text items. You can choose one or multiple choices from the list. The syntax of declaring a ListBox is:
listbox_tk = Listbox( window, features )
Listbox features and properties are:
1 | bg | Decides the background color of the widget |
2 | borderwidth | Decides the border width of the widget. |
3 | cursor | Shows the type of cursor when the mouse is hovered over the listbox. The default is a pointed arrow cursor. |
4 | font | Determines the type of font that is used for the lisbtox items. |
5 | fg | Determines the foreground color of font that is used for the listbox items. |
6 | height | Determines the height of the listbox widget. The default value is 10. |
7 | highlightcolor | Determines the color of the Listbox under focus |
8 | highlightthickness | Planks the thickness of the highlight border |
9 | relief | Sets the border type. The default is FLAT |
10 | selectbackground | Background color of the selected text |
11 | selectmode | This mode is used to determine the number of items that we can select from the list. There are multiple options that you can set to use the selectmode like BROWSE, SINGLE, MULTIPLE and EXTENDED. |
12 | width | Determines the width of widget. Default is 20. |
13 | xscrollcommand | Lets the user scroll the Listbox horizontally. |
14 | yscrollcommand | Lets the user scroll the Listbox vertically. |
Listbox methods are:
1 | activate(index) | Activates the given item of the list. This item is known as the ACTIVE index. |
2 | curselection() | This method shows the indices of the selected item of the listbox. |
3 | delete(first, last = None) | Deletes items in a Listbox within the given range. |
4 | get(first, last = None) | Gets items from the listbox within the given range. |
5 | index(i) | It is used to position the index line at the top of the widget. |
6 | insert(index, *elements) | Insert method is used to add lines index wise. |
7 | nearest(y) | Returns the nearest index when you provide the given coordinate in the Listbox |
8 | see(index) | Makes the index visible. |
9 | size() | Shows the total number of items present in the list. |
10 | xview() | This is used to make the widget horizontally scrollable. |
11 | yview() | This is used to make the widget vertically scrollable. |
Creating Listbox Widget
You can create a simple listbox as follows:
from tkinter import * screen = Tk() screen.geometry('400x400') #Colors of a pallette label_tk = Label(text="A list of colors:") #Creating a List color_box = Listbox() color_box.insert(1,"Red") color_box.insert(2,"Green") color_box.insert(3,"Yellow") color_box.insert(4,"Blue") label_tk.pack() color_box.pack() screen.mainloop()
Output will be:
References have been used from here