Getting the text from a Listbox item
Solution 1
If you want to get every item of the Listbox then you can use this. Keep in mind that what is returned is a tuple
.get(0, tk.END)
If you want the item(s) from the current selection then you can use this. Keep in mind that what is returned is a tuple
.curselection()
However, this only gives you the indexes of the selected items. To get the text simply use something like this. Using the index values from .curselection()
to get the items from the entire selection
import tkinter as tk
l_box = tk.Listbox(...)
all_items = l_box.get(0, tk.END) # tuple with text of all items in Listbox
sel_idx = l_box.curselection() # tuple with indexes of selected items
sel_list = [all_items[item] for item in sel_idx] # list with text of all selected items
Solution 2
You can use the following:
import tkinter as tk
listbox = tk.listbox(...)
value=listbox.get(listbox.curselection())
print (value)
![Jonah Fleming](https://lh4.googleusercontent.com/-nT_-2fs9ykY/AAAAAAAAAAI/AAAAAAAAABI/n9DanYw3AEk/photo.jpg?sz=256)
Jonah Fleming
I am a new Python programmer who likes creating and distributing free Tkinter apps. I am SOreadytohelp
Updated on June 04, 2022Comments
-
Jonah Fleming about 2 years
I am creating a session list and pickling the sessions afterwards. This bit works but when I delete the session from the listbox with a right click menu, I need to be able to delete the item from the list I am pickling.
How do I get the text in the current listbox selection?
Here is my code:
class Main(self, root) def __init__(self): self.f2=Frame(root) self.f2.grid() Label(self.f2, text="Sesion Date:").grid(row=3, column=0) self.e=Entry(self.f2) self.e.grid(row=3, column=1) Button(self.f2, text="Add Session", command=lambda: self.session(client)).grid(row=4, columnspan=2) scrollbar=Scrollbar(self.f2) self.sessionbox=Listbox(self.f2, yscrollcommand=scrollbar.set) self.sessionbox.grid(row=5, columnspan=2) self.sessionmenu=Menu(self.sessionbox, tearoff=0) self.sessionmenu.add_command(label="Delete", command=lambda: self.deleteSession(client)) self.sessionbox.bind("<ButtonRelease-2>", self.sessionRightClick) scrollbar.config(command=self.sessionbox.yview) def session(self, client): if len(self.e.get()) == 0: tkMessageBox.showinfo("Add Session", "Please type a session date\nbefore submitting") else: self.sessionlist=[] self.sessionlist.append("%s" % (self.e.get())) self.sessionbox.insert(0, "%s" % (self.e.get())) with open("sessions", "wb") as f: pickle.dump(self.sessionlist, f) self.e.delete(0, END) self.row1+=1 def deleteSession(self, client): try: sel=self.sessionbox.curselection() self.sessionbox.delete(sel) self.sessionlist.remove() with open("sessions", "wb") as f: pickle.dump(self.sessionlist, f) except: tkMessageBox.showerror("Delete Session", "No session selected!") def sessionRightClick(self, event): self.sessionmenu.post(event.x_root, event.y_root) root=Tk() app=Main(root) root.mainloop()