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

2023-12-23

我想知道如何获取启用自动换行的 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()

但适用于非换行文本的方法,例如:

int(text_widget.index('end-1c').split('.')[0]) 

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

感谢您的帮助 !


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

它打印

显示行: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()

or with 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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐