可以强制 tkinter.Text 小部件在“空格”字符以及单词上换行吗?

huangapple go评论56阅读模式
英文:

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(&#39;&lt;KeyPress-space&gt;&#39;, self.char_space)
        self.tag_configure(&#39;space&#39;, wrap=&#39;char&#39;)
    
    def char_space(self, event=None) -&gt; str:
        self.insert(&#39;insert&#39;, &#39; &#39;, &#39;space&#39;)
        return &#39;break&#39;

       
text = Text(root, wrap=&#39;word&#39;, width=40, height=10)
text.pack(expand=True, fill=&#39;both&#39;)

    
if __name__ == &#39;__main__&#39;:
    root.mainloop()

huangapple
  • 本文由 发表于 2023年3月7日 23:04:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定