我想知道如何获取启用了自动换行的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)?
感谢您的帮助!
答案 0 :(得分:1)
使用“缺失计数方法”的工作示例
打印
displaylines: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()
或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()