如何将tkinter ListBox转换为列表?

时间:2014-04-23 02:19:15

标签: python tkinter

我有一个tkinter ListBox,当然还有一定数量的商品。

我需要使用ListBox上存储的信息保存.txt文件。

我尝试了很多方法,但它不会起作用。有任何想法吗 ?谢谢!

1 个答案:

答案 0 :(得分:2)

使用Tkinter.Listbox.get()Tkinter.Listbox.curselection()

如果您想要列表框中的所有条目,请尝试以下操作:

print self.lb.get(0,Tkinter.END)

如果您想要所选的条目:

print [self.lb.get(i) for i in self.lb.curselection()]

充实示例:

# UNTESTED

# Assuming you have an event bound to "OnClick":
def OnClick(self):
  with open("savefile.txt", "w") as savefile:
    # Assuming your listbox is stored in "self.lb"
    savefile.write('\n'.join(self.lb.get(i) for i in self.lb.curselection())
    savefile.write('\n')