python - tkinter Text() 小部件上的 4096 单行字符限制?

标签 python windows user-interface tkinter

我遇到了一个关于 Tkinter 中的 Text 小部件的有趣问题,我似乎无法理解。谷歌也没有提供答案。当禁用文本换行时,Tkinter 似乎对 4096 个字符的 Text() 小部件有单行字符限制。有没有办法更改此限制或在 4095 个字符后强制文本换行?我在其他小部件上看到了 wraplength 参数,但没有看到 Text 小部件。

示例代码:

import Tkinter as tk

if __name__ == "__main__":
    root = tk.Tk()
    text = tk.Text(root)
    sb = tk.Scrollbar(root, orient="horizontal", command=text.xview)
    text.configure(xscrollcommand=sb.set)
    text.configure(wrap=tk.NONE)
    text.pack(fill="both", expand=True)
    sb.pack(side="bottom", fill="x")

    text.insert("end","a"*4095)
    text.insert("end","\n")
    text.insert("end","b"*4096)
    text.insert("end","\n")
    text.insert("end","c"*4095)

    root.mainloop()

真正奇怪的是,如果您单击或突出显示应该打印“b”的位置,它们会突然出现吗?为什么他们首先消失了?

Python 版本:2.7.5

操作系统:Windows 7

更新:

这似乎是 Windows 7 的平台问题。仍然不确定为什么会发生或是否可以轻松修复。

截图:

这是应用程序首次启动时的样子。 'b's 丢失了:

enter image description here

一旦我给出 'b' 的焦点,它们就会突然出现:

enter image description here

一旦我从 'b' 上移开焦点,它们就会消失。

最佳答案

我在另一个网站上找到了部分解决方案: here

它的工作原理是将文本小部件子类化以观察行的长度并在达到限制时插入一个额外的换行符

import Tkinter as tk

class WrapText(tk.Text):
    def __init__(self, master, wraplength=100, **kw):
        tk.Text.__init__(self, master, **kw)
        self.bind("<Any-Key>", self.check)
        self.wraplength = wraplength-1 

    def check(self, event=None):
        line, column = self.index(tk.INSERT).split('.')
        if event and event.keysym in ["BackSpace","Return"]: pass
        elif int(column) > self.wraplength: 
            self.insert("%s.%s" % (line,column),"\n")

    def wrap_insert(self, index, text):
        for char in text:
            self.check()
            self.insert(index, char)

if __name__ == "__main__":
    root = tk.Tk()
    text = WrapText(root, wraplength=4000)
    sb = tk.Scrollbar(root, orient="horizontal", command=text.xview)
    text.configure(xscrollcommand=sb.set)
    text.configure(wrap=tk.NONE)
    text.pack(fill="both", expand=True)
    sb.pack(side="bottom", fill="x")

##    text.tag_config("mystyle", background="yellow", foreground="red", wrap="char")

    text.wrap_insert("end","a"*4095)#,"mystyle")
    text.wrap_insert("end","\n")
    text.wrap_insert("end","b"*4095)
    text.wrap_insert("end","\n")
    text.wrap_insert("end","c"*4095)

    root.mainloop()

这个方法有几个明显的局限性,首先它实际上是在输入的数据中添加字符(这可能是不可取的),其次它只是按字符换行,所以它可以在一个单词的中间换行,但是还有一些方法可以实现这一点。

关于python - tkinter Text() 小部件上的 4096 单行字符限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28906319/

相关文章:

windows - git for windows - 启动时不加载 %USERPROFILE%\.gitconfig "run as"

python - 使用 Windows 在 Heroku 上部署 python flask web 应用程序

java - 如何通过右键单击Swing中的面板来绘制形状?

Python 内存错误 - Numpy 矩阵 (1568x1568)

python - 雅虎状态检测

windows - 我的应用程序如何找到 Windows 消息的发件人?

java - JLabel 不会改变颜色两次

android - 如何获得收藏之星

Python 字符串中的特殊字符

python - Django Rest Framework 的测试请求无法由其自己的 Request 类解析