【问题标题】:Missing `count` method in Tkinter's Text widgetTkinter 的文本小部件中缺少“计数”方法
【发布时间】:2015-11-18 15:57:26
【问题描述】:

我正在尝试获取 Tkinter Text 小部件中显示的行数,我正在查看这个问题:What's the most efficient way to get a Tkinter Text widget's total display lines after the insert?

我感兴趣的解决方案使用小部件的 count 方法,但在我的 Python 2.7.10(Tk 8.5,Tcl 8.5)上,文本小部件没有该属性。

import Tkinter

root = Tkinter.Tk()
text = Tkinter.Text()
text.pack()

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

text.insert("1.0", "a" * 81)
text.insert("2.0", "b\n")
text.bind('<Map>', test)

root.mainloop()

产量

AttributeError: Text instance has no attribute 'count'

从我发现的文档中它应该在那里;我错过了什么吗?

【问题讨论】:

    标签: python-2.7 tkinter


    【解决方案1】:

    这似乎是 Tkinter 中的一个错误。你可以使用monkeypatch来添加缺失的方法:

    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
    
    Tkinter.Text.count = count_monkeypatch
    

    【讨论】:

    • 感谢您的确认。我有点疯狂地试图了解发生了什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    相关资源
    最近更新 更多