从列表框项中获取文本

时间:2015-12-06 03:01:27

标签: python list tkinter listbox 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()

2 个答案:

答案 0 :(得分:3)

如果您想获取Listbox的每个项目,那么您可以使用它。请记住,返回的内容是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

答案 1 :(得分:0)

您可以使用以下内容:

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

value=listbox.get(listbox.curselection())
print (value)
相关问题