Tkinter-使用自动换行计数文本小部件中的行

Xoo*_*oot 5 python tkinter

我想知道如何在启用了自动换行的Tkinter Text小部件中获取行数。

在此示例中,文本小部件中有3行:

from Tkinter import *

root = Tk()
text = Text(root, width = 12, height = 5, wrap = WORD)
text.insert(END, 'This is an example text.')
text.pack()

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

但是适用于非包装文本的方法,例如:

int(text_widget.index('end-1c').split('.')[0]) 
Run Code Online (Sandbox Code Playgroud)

将返回1而不是3。是否有另一种方法可以正确计算换行(在我的示例中返回3)?

谢谢你的帮助 !

fur*_*ras 4

使用“缺失计数方法”的工作示例

它打印

显示行数: 3
行数: 1

from Tkinter import *

def count_monkeypatch(self, index1, index2, *args):
    args = [self._w, "count"] + ["-" + arg for arg in args] + [index1, index2]

    result = self.tk.call(*args)
    return result

Text.count = count_monkeypatch


root = Tk()
text = Text(root, width = 12, height = 5, wrap = WORD)
text.insert(END, 'This is an example text.')
text.pack()

def test(event):
    print "displaylines:", text.count("1.0", "end", "displaylines")
    print "lines:", text.count("1.0", "end", "lines")

text.bind('<Map>', test)

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

或用Button代替bind

from Tkinter import *

#-------------------------------------------

def count_monkeypatch(self, index1, index2, *args):
    args = [self._w, "count"] + ["-" + arg for arg in args] + [index1, index2]

    result = self.tk.call(*args)
    return result

Text.count = count_monkeypatch

#-------------------------------------------

def test(): # without "event"
    print "displaylines:", text.count("1.0", "end", "displaylines")
    print "lines:", text.count("1.0", "end", "lines")

#-------------------------------------------

root = Tk()
text = Text(root, width = 12, height = 5, wrap = WORD)
text.insert(END, 'This is an example text.')
text.pack()

Button(root, text="Count", command=test).pack()

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

  • 在新版本的 Tkinter 中 `t.count('1.0', 'end', 'displaylines')` 无需猴子补丁即可工作。 (2认同)