英文:
Can I force the tkinter.Text widget to wrap lines on the "space" character as well as words?
问题
以下是一个示例 tkinter 应用程序,其中有一个“Text”字段,长单词会换行到下一行,如预期。然而,问题在于空格不会以相同的方式换行到下一行。在开始新单词之前,我可以输入任意数量的空格,不会发生换行。一旦我开始输入任何其他可打印字符(以及制表符和换行符),文本会按预期换行。
我如何配置我的“Text”小部件,以便在行尾的空格上也进行换行?除了像使用Text.count()
来解析特定行的长度(也许),并在width
个字符之后强制换行之外,是否有更好的方法?
import tkinter as tk
root = tk.Tk()
text = tk.Text(root, wrap='word', width=40, height=10)
text.pack(expand=True, fill='both')
if __name__ == '__main__':
root.mainloop()
英文:
Below is an example tkinter app with a Text
field which wraps to the next line on long words, as expected. The issue, however, is that spaces don't wrap to the next line in the same way. I am able to enter as many spaces as I like prior to the start of a new word and a line wrap won't occur. Once I begin typing any other printable characters (as well as tabs and newlines), the text wraps as expected.
How can I configure my Text
widget to also wrap on whitespace at the end of the line? Is there a better method than, say, parsing out the length of the line in question (with Text.count()
, perhaps) and forcing a newline after width
characters?
import tkinter as tk
root = tk.Tk()
text = tk.Text(root, wrap='word', width=40, height=10)
text.pack(expand=True, fill='both')
if __name__ == '__main__':
root.mainloop()
答案1
得分: 1
以下是您要翻译的代码部分:
import tkinter as tk
root = tk.Tk()
class Text(tk.Text):
def __init__(self, master, **kwargs):
tk.Text.__init__(self, master, **kwargs)
self.bind('<KeyPress-space>', self.char_space)
self.tag_configure('space', wrap='char')
def char_space(self, event=None) -> str:
self.insert('insert', ' ', 'space')
return 'break'
text = Text(root, wrap='word', width=40, height=10)
text.pack(expand=True, fill='both')
if __name__ == '__main__':
root.mainloop()
如您所要求,我只提供了代码的翻译部分,没有其他内容。
英文:
Simply wrap spaces in a tag
with wrap
option set to "char".
import tkinter as tk
root = tk.Tk()
class Text(tk.Text):
def __init__(self, master, **kwargs):
tk.Text.__init__(self, master, **kwargs)
self.bind('<KeyPress-space>', self.char_space)
self.tag_configure('space', wrap='char')
def char_space(self, event=None) -> str:
self.insert('insert', ' ', 'space')
return 'break'
text = Text(root, wrap='word', width=40, height=10)
text.pack(expand=True, fill='both')
if __name__ == '__main__':
root.mainloop()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论