将列表框的内容复制到文本文件

时间:2017-04-28 21:27:08

标签: python python-3.x tkinter listbox

我在TkInter中有一个正常运行的列表框,我正在尝试创建一个允许用户删除一行数据的函数。列表框的内容来自文本文件(userfile)。我希望能够从列表框中选择一行,并将其从列表框和文本文件中删除。我目前通过curselection从列表框中删除该行,但不是从相应的文本文件中删除。我不知道是否可以从文本文件中删除某一行,并想知道将列表框的内容复制到文本文件是否是最好的方法?

def Delete():

    global rootD
    global userfile
    global listbox1

    rootD = Tk()
    rootD.title('Delete info')

    fin = open(userfile, 'r')
    mylist = fin.readlines()
    fin.close()

    listbox1 = Listbox(rootD, width=50, height=6)
    listbox1.grid(row=0, column=0)
    yscroll = Scrollbar(command=listbox1.yview, orient=VERTICAL)
    yscroll.grid(row=0, column=1, sticky=N + S)
    listbox1.configure(yscrollcommand=yscroll.set)

    enter1 = Label(rootD, text='Click on the line to delete', width=50)
    enter1.grid(row=1, column=0)

    for item in mylist:
        listbox1.insert(END, item)

    delButton = Button(rootD, text='Delete', command=Remove)
    delButton.grid(columnspan=2, sticky=W)
    delButton.grid(row=2, column=0)

def Remove():

    global listbox1
    global nameEL          # a previous input for the username
    global userfile

    try:
        index = listbox1.curselection()[0]
        listbox1.delete(index)
        newfile = nameEL.get() + '.txt'
        with open(newfile, 'w') as u:
            u.write(listbox1.get(0, END))
            u.write('\n')
            u.close()
    except IndexError:
        pass

1 个答案:

答案 0 :(得分:0)

with open(file, 'w') as f:
    f.write(''.join(listbox1.get(0, END)))
    f.write('\n'
    f.close()