PascalVKooten
PascalVKooten

Reputation: 21433

Tkinter Text Widget, iterating over lines

If I have a tkinter Text widget filled with the following:

/path/to/file/1.txt
/path/to/file/2.txt
/path/to/file/3.txt

Is there a direct way to iterate over all lines (for instance, to open a file, perform an action, and write)?

Upvotes: 4

Views: 2864

Answers (1)

falsetru
falsetru

Reputation: 368894

text_widget.get('1.0', 'end-1c') returns whole text content as string. Split it using 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()

Upvotes: 6

Related Questions