簡體   English   中英

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

[英]4096 single line character limit on tkinter Text() widget?

關於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'缺失:

在此輸入圖像描述

一旦我給出'b'的焦點,他們突然出現:

在此輸入圖像描述

一旦我從'b'移開焦點,他們就會消失。

我在另一個網站上找到了部分解決方案: 這里

它通過子類化文本小部件來觀察行長度並在達到限制時插入額外的換行符

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()

這個方法有幾個明顯的局限性,首先它實際上是為輸入的數據添加字符(這可能是不可取的),其次它只是按字符包裝,所以它可以包裝在一個單詞的中間,但有一些方法其中也可以實施。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM