如何将 tkinter ListBox 转换为列表?

rod*_*rod 2 python tkinter

我有一个 tkinter ListBox,当然,上面存放着一定数量的项目。

我需要保存一个 .txt 文件,其中包含列表框中存储的信息。

我尝试了很多方法但行不通。有任何想法吗 ?谢谢 !

Rob*_*obᵩ 5

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

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

print self.lb.get(0,Tkinter.END)
Run Code Online (Sandbox Code Playgroud)

如果您想要选定的条目:

print [self.lb.get(i) for i in self.lb.curselection()]
Run Code Online (Sandbox Code Playgroud)

充实这个例子:

# 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')
Run Code Online (Sandbox Code Playgroud)