How to Read the Listbox Selection in Python
Learning how to read the text of a selected item in a ListBox control using Python can make your application more flexible. A ListBox control is used to display items from where you can select and use in your program. In Python, you can create controls such as list boxes and buttons which you can use to capture information from the user. Use the “curselection()” method to retrieve the index selected then use the “get()” method to retrieve the text of the index.
Instructions
-
-
1
Launch IDLE (Python GUI), click the “File” menu and click “New Window” to create a new window. Press “Ctrl” and “S” to launch the “Save As” dialog window. Type “readListBox” next to “File name:“ and click “Save.”
-
2
Copy and paste the following code to import the namespace required for this project and create the ListBox widget:
from Tkinter import *
mainWin = Tk()
lstBox = Listbox(mainWin)
lstBox.pack() -
-
3
Add the following code to create the button “callback” event and display the text of the item selected using the prompt window:
def callback():
sIndex = lstBox.curselection()
itmText = lstBox.get(sIndex)
print itmText -
4
Copy and paste the following code to create the button widget:
btn = Button(mainWin, text="Get Text", command=callback)
btn.pack() -
5
Add the following code to populate the ListBox widget with four items:
lstBox.insert(END, "Item List:")
for item in ["item one", "item two", "item three", "item four"]:
lstBox.insert(END, item)
mainloop() -
6
Click the “Windows” start button and type “Cmd” in the “Search programs and files” text box. Press “Enter” to open the command prompt window. Navigate to C:\Python<version number>\ and type “python readListBox.” Press “Enter” to run your project. Click an item on the ListBox and click the “Get Text” button to display the text of the item selected.
-
1