如何从长字符串列表中打印50个单词

时间:2017-10-07 14:50:19

标签: python python-2.7 python-3.x list tkinter

我试图从字符串列表中显示tkinter窗口中的文本。但是问题是字符串很长,我希望它在一行中只显示50个字符然后在下一个中休息50,以便完整字符串。

news_full=['Finance Minister Arun Jaitley said on Friday that the rules for small businesses and exporters would be eased under the Goods and Services Tax (GST), a move that could provide relief to thousands of small firms.', 'Employers may now have more leeway to withhold birth control coverage on religious grounds, according to new rules issued by the US Department of Health and Human Services.', "Samantha Ruth Prabhu and Naga Chaitanya tied the knot on Friday evening. And we need to thank Naga's father and actor Nagarjuna Akkineni for sharing the first pictures of the couple. Here are the latest photos from Samantha Ruth Prabhu and Naga Chaitanya's grand Goa wedding. Scroll on.", 'The storm brought heavy rain to Central America, where more than 20 people died. The storm is headed toward Louisiana, where Gov. John Bel Edwards said, "I\'m not going to tell you I am not concerned."', "A police official said investigators don't think anyone else was in the shooter's room before the Las Vegas attack, but are looking if anyone knew about his plans.", "MELBOURNE, Australia (AP) — Australia cricket captain Steve Smith will return home from the team's tour of India with a right shoulder injury, Cricket Australia said Saturday.", 'Hurricane Nate gained force as it headed toward the central Gulf of Mexico early Saturday after drenching Central America in rain that was blamed for 21 deaths.', 'India, meanwhile, said there were “no new developments” at the face-off site, and that the status quo continues.', 'The possible sale of the advanced system can go ahead if congress does not object within 30 days.', 'Thousands of people gather at 40 locations across the country on Saturday as part of the Stop Adani Alliance']

root=Tk()

for s in news_full:
    texr2=Label(root,text=s,font=("sans-serif",32))
    texr2.pack()

root.geometry('545x800')

root.mainloop()
  

所以预期的输出是(ex为列表的第一个元素)

Finance Minister Arun Jaitley said on Friday that 
the rules for small businesses and exporters would
be eased under the Goods and Services Tax (GST), 
a move that could provide relief to thousands of 
small firms.

列表的所有元素都相同。

2 个答案:

答案 0 :(得分:1)

您可以在创建wraplength对象时使用Label来自行进行文本换行。

这是以屏幕为单位给出的,因此如果您的窗口宽度为545像素(如您的示例所示),则可以传递wraplength值545,使其包裹在您的窗口中。

要使文字与预期输出中的左侧对齐,您可以传递参数justify=LEFTanchor=W

您创建标签的行如下所示:

texr2=Label(root, text=s, wraplength=545, anchor=W, justify=LEFT, font=("sans-serif",14))

请注意,我更改了字体大小,以便所有文字都符合窗口大小。

您还希望通过打包fill=BOTHexpand=True参数来确保所有内容都正确填充:

texr2.pack(expand=True, fill=BOTH)

答案 1 :(得分:0)

如果可能的话,当然要使用TK的自动包装。但如果没有,您可以执行以下操作:

from textwrap import wrap

s = "Some very long string. Or short. It does not matter really. Blah, blah, blah!\nIt can be multilined too!"
print "\n".join(wrap(s, 25))

所以这会将每行文本换行为25个字符。将返回一个行列表。