从列表框项中获取文本

Getting the text from a Listbox item

我正在创建一个会话列表,然后对会话进行 pickle。这一点有效,但是当我使用右键单击菜单从列表框中删除会话时,我需要能够从我正在酸洗的列表中删除该项目。

如何获取当前列表框选择中的文本?

这是我的代码:

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()

如果你想获取列表框中的每一项,那么你可以使用它。请记住,返回的是 tuple

.get(0, tk.END)

如果您想要当前选择的项目,那么您可以使用它。请记住,返回的是 tuple

.curselection()

但是,这只会为您提供所选项目的索引。要获取文本,只需使用类似这样的东西。使用 .curselection() 中的索引值从整个选择中获取项目

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

您可以使用以下内容:

import tkinter as tk
listbox = tk.listbox(...)

value=listbox.get(listbox.curselection())
print (value)