newfile.py
newfile.py

Reputation: 63

How to automatically add '\n' To paragraph

I have a long paragraph, I split it using '\n' and use it in canvas. I don't want to do the same thing in every paragraph, because I will have too many paragraphs. Is there a way for me to automatically insert the '\n' in certain parts of the paragraph?

from tkinter import *

w = Tk()

canvas = Canvas(width = 800, height = 800)
canvas.place(relx=0, rely=0)

paragraph = "Lorem ipsum dolor sit amet, consectetur\nadipiscing elit. Nam sollicitudin rhoncus\nipsum. Morbi sed metus sollicitudin, tristique\nsapien vitae, cursus nulla. Mauris vel accumsan\npurus. Vestibulum orci est, euismod non ultricies\nporttitor, blandit at mi. Integer ut lectus congue,\nfinibus magna a, mattis erat. Proin quis egestas\nligula."

canvas.create_text(50, 50, text=paragraph, anchor=NW, font="Times 5 bold")

w.mainloop()

Upvotes: 1

Views: 437

Answers (2)

Beto Nogueira
Beto Nogueira

Reputation: 13

If "certain parts" means a number of words or some lenght, you can write a function do add \n for you based on that.

Upvotes: 1

tdelaney
tdelaney

Reputation: 77347

use the textwrap module. For the example I unwrapped the paragraph by removing newlines, but you wouldn't do that in cases where text was wrapped manually.

from tkinter import*
import textwrap

w=Tk()

canvas =Canvas(width = 800, height = 800)
canvas.place(relx=0,rely=0)

paragraph="Lorem ipsum dolor sit amet, consectetur\nadipiscing elit. Nam sollicitudin rhoncus\nipsum. Morbi sed metus sollicitudin, tristique\nsapien vitae, cursus nulla. Mauris vel accumsan\npurus. Vestibulum orci est, euismod non ultricies\nporttitor, blandit at mi. Integer ut lectus congue,\nfinibus magna a, mattis erat. Proin quis egestas\nligula."

# lazy way to get rid of the newlines for test
paragraph = paragraph.replace("\n", " ")
wrapped = textwrap.fill(paragraph, 40)

canvas.create_text(50,50,text=wrapped,anchor=NW,font="Times 5 bold")

w.mainloop()

Upvotes: 1

Related Questions