显示行号有两种意思:在每行前显示一个阿拉伯数字行号,类似其他IDE。这种直接计算出 ScrolledText 控件的行高,再用一个 Label 控件写上数字放在左边布局即可。
显示当前光标的行号,这里需要用到 tk.CURRENT 标记,Python3 代码如下。以下代码显示了当前光标位置的行号和行内字符偏移。
import tkinter as tk
from tkinter import scrolledtext, messagebox
win = tk.Tk()
scr = scrolledtext.ScrolledText(win, width=60, height=20, wrap=tk.WORD)
scr.pack()
def on_click():
messagebox.showinfo(title=None, message=scr.index(tk.CURRENT))
btn = tk.Button(win, text="Click", command=on_click)
btn.pack()
win.mainloop()
由于 Python 内置的 tkinter 只是 tcl/tk 的一层面向对象包装,所以,主要需要查询的文档都在TclTk中。
上述代码参考的方法和常量来自:https://www.tcl.tk/man/tcl8.6/TkCmd/text.htmwww.tcl.tkTwo marks have special significance. First, the mark insertis associated with the insertion cursor, as described under currentis associated with the character closest to the mouse and is adjusted automatically to track the mouse position and any changes to the text in the widget (one exception: currentis not updated in response to mouse motions if a mouse button is down; the update will be deferred until all mouse buttons have been released). Neither of these special marks may be deleted. With the exception of these two special marks, all marks are shared between peer text widgets, and may be manipulated on an equal basis from any peer.