获取 Text tkinter 小部件的行数 [英] Get of number of lines of a Text tkinter widget
问题描述
我得到 tkinter Text
小部件的行数,如下所示:
I get the number of lines of a tkinter Text
widget like this:
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()
唯一的问题:当你点击
时,行数没有增加.您需要添加一些其他文本,以便增加行数.
Only problem : when you hit <Return>
, the count of lines doesn't increase. You need to add some futher text in order that count of lines increases.
如何做到这一点 <Return > 键增加行数?
推荐答案
不要获取所有的文本然后计数,只需用 index("end-1c")
然后做一些字符串操作来获取行号.
Don't get all the text and then count, just get the index of the last-minus-one character with index("end-1c")
and then do some string manipulation to get the line number.
至于为什么数字没有增加,那是因为您的绑定发生在之前插入返回键.对于您的简单测试,您可以通过绑定 <KeyRelease>
来解决此问题,因为字符已插入到印刷机上.
As for why the number doesn't increase, it's because your binding happens before the return key is inserted. For your simple test you can work around this by binding on <KeyRelease>
, since the character is inserted on the press.
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"的高级功能.对此问题的回答中简要介绍了绑定标签:关于绑定标签的基本查询tkinter.简而言之,您必须创建一个出现在类 bindtag 之后的自定义 bindtag,以便您的绑定发生在类绑定之后.
If you need to print the value on the key press, you'll have to use an advanced feature called "bindtags". Bindtags are covered briefly in an answer to this question: Basic query regarding bindtags in tkinter. In short, you have to create a custom bindtag that appears after the class bindtag, so that your binding happens after the class binding.
以下是修改程序以使用绑定标签的方法:
Here's how to modify your program to use bindtags:
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()
这篇关于获取 Text tkinter 小部件的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!