Tkinter Text Widget,遍历行

Pas*_*ten 3 python tkinter python-3.x

如果我有一个填充以下内容的 tkinter Text 小部件:

/path/to/file/1.txt
/path/to/file/2.txt
/path/to/file/3.txt
Run Code Online (Sandbox Code Playgroud)

是否有直接的方法来遍历所有行(例如,打开文件、执行操作和写入)?

fal*_*tru 5

text_widget.get('1.0', 'end-1c')以字符串形式返回整个文本内容。使用str.splitlines().

from tkinter import *

def iterate_lines():
    for line in t.get('1.0', 'end-1c').splitlines():
        # Iterate lines
        if line:
            print('path: {}'.format(line))

root = Tk()
t = Text(root)
t.insert(END, '/path/to/file/1.txt\n/path/to/file/2.txt\n/path/to/file3.txt\n')
t.pack()
Button(root, text='iterate', command=iterate_lines).pack()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)