我正在使用 Python 开发一个简单的 GUI 代码编辑器,我希望始终突出显示光标所在的文本行。
现在,我的 TextEditor
类看起来像:
class TextEditor:
def __init__(self, container):
self.scrollbar = Scrollbar(container)
self.scrollbar.pack(side=RIGHT, fill=Y)
self.textbox = Text(container, height=40, undo=True, width=80,
font=tkFont.Font(family="Consolas", size=12))
self.textbox.pack(side=LEFT)
self.textbox.config(yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.textbox.yview)
我该怎么做?
最佳答案
tkinter 没有直接支持它的内置内容。然而,对于大多数用途来说已经足够好的东西是编写一个轮询光标位置并定期更新突出显示的函数。
例如:
import Tkinter as tk
class MyApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.text = tk.Text(self)
self.text.pack(side="top", fill="both", expand=True)
self.text.tag_configure("current_line", background="#e9e9e9")
self._highlight_current_line()
def _highlight_current_line(self, interval=100):
'''Updates the 'current line' highlighting every "interval" milliseconds'''
self.text.tag_remove("current_line", 1.0, "end")
self.text.tag_add("current_line", "insert linestart", "insert lineend+1c")
self.after(interval, self._highlight_current_line)
app = MyApp()
app.mainloop()
显然,时间间隔越长,引入的“滞后”就越多,时间间隔越短,使用的 CPU 就越多,但在几乎没有可察觉的滞后和难以察觉的两种极端情况之间有一个相当大的甜蜜点CPU 使用率激增。
还有另一种方法可以做到这一点,它不涉及轮询,而且绝对万无一失。您可以将突出显示精确地移动到插入光标实际移动的时间,但它涉及编写一些嵌入式 Tcl 代码来创建隐藏在 Tkinter Text
对象实现中的实际 tk 小部件的代理。
最后,第三种方法是为所有可能修改光标位置的事件设置自定义绑定(bind)。虽然可能,但很难做到 100% 正确,因为您必须考虑所有 修改光标位置的事件,以及处理代码中可能不使用事件而移动光标的位置。不过,使用绑定(bind)是一个非常好的解决方案,只是需要多做一些工作。
关于python - 如何突出显示文本小部件的当前行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9691205/