[英]Get number from a line of a txt file and use it as input to extract lines
[英]Python Tkinter listbox input from txt file multiple lines are showing in one line
我的问题很简单。 我正在根据以下代码将列表框保存到 txt 文件中:
def file_save():
global filename
if filename == '':
filename = filedialog.asksaveasfile(mode='w', defaultextension=".txt")
if filename is not None:
for i in textentry.get(0,END):
filename.write(i+"\n")
我的列表框包含多行,例如
aa
bb
cc
而我的 txt output 也是这样。
但是当我将此 txt 文件加载到我的空列表框中时。 表明
aabbcc
我的加载代码如下:
def file_open():
global filename
filename = filedialog.askopenfile(mode='r+', filetypes =[('Txt', '*.txt')])
if filename is not None:
t = filename.read()
textentry.delete(0, 'end')
for item in t:
textentry.insert(END, item)
#textentry.insert(END, t)
textentry.focus()
我尝试for item in t:
,它显示
a
a
b
...
textentry.insert(END, t)
显示 aabbcc
我需要将我加载的 txt 文件显示为
aa
bb
cc
谢谢
使用readlines
而不是read
:
from tkinter import filedialog, Listbox, Tk
top = Tk()
textentry = Listbox(top)
filename = filedialog.askopenfile(mode='r+', filetypes =[('Txt', '*.txt')])
if filename is not None:
t = filename.readlines()
textentry.delete(0, 'end')
for item in t:
textentry.insert('end', item)
textentry.focus()
textentry.pack()
top.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.