我得到一个 tkinter 的行数 Text
像这样的小部件:
import Tkinter as Tk
def countlines(event):
print float(event.widget.index(Tk.END))-1
print event.widget.get("1.0", Tk.END).count("\n")
root = Tk.Tk()
root.geometry("200x200")
a = Tk.Text(root)
a.pack()
a.bind("<Key>", countlines)
root.mainloop()
唯一的问题:当你点击 <Return>
时,行数不会增加。您需要添加一些进一步的文本以增加行数。
如何让
最佳答案
不要获取所有的文本然后计数,只获取带index("end-1c")
的最后一个减一字符的索引。然后做一些字符串操作来获取行号。
至于为什么数字没有增加,那是因为你的绑定(bind)发生在插入返回键之前。对于您的简单测试,您可以通过绑定(bind) <KeyRelease>
来解决这个问题, 因为字符是按插入的。
import Tkinter as Tk
def countlines(event):
(line, c) = map(int, event.widget.index("end-1c").split("."))
print line, c
root = Tk.Tk()
root.geometry("200x200")
a = Tk.Text(root)
a.pack()
a.bind("<KeyRelease>", countlines)
root.mainloop()
如果需要在按键时打印值,则必须使用称为“bindtags”的高级功能。在这个问题的回答中简要介绍了绑定(bind)标签:Basic query regarding bindtags in tkinter .简而言之,您必须创建一个出现在类绑定(bind)标签之后的自定义绑定(bind)标签,以便您的绑定(bind)发生在类绑定(bind)之后。
以下是修改程序以使用绑定(bind)标签的方法:
import Tkinter as Tk
def countlines(event):
(line, c) = map(int, event.widget.index("end-1c").split("."))
print line, c
root = Tk.Tk()
root.geometry("200x200")
a = Tk.Text(root)
a.pack()
bindtags = list(a.bindtags())
bindtags.insert(2, "custom")
a.bindtags(tuple(bindtags))
a.bind_class("custom", "<Key>", countlines)
root.mainloop()
关于python - 获取文本 tkinter 小部件的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20565149/