python - 在 Tkinter Text 小部件中突出显示整个行长
问题描述
除了我希望突出显示的区域跨越文本小部件的宽度之外,此示例工作正常。我的第一个想法是使用空格填充字符串,ljust
但由于 Text 小部件将填充不同的字体类型,因此它不起作用。
有没有办法突出整行?
import tkinter as tk
def highlight(n):
text.tag_add("highlight", "{}.0".format(n), "{}.end".format(n))
def remove_highlight(n):
text.tag_remove("highlight", "{}.0".format(n), "{}.end".format(n))
root = tk.Tk()
text = tk.Text(root, width=30, height=3, wrap=None)
text.pack()
text1 = "text"
text2 = "text2"
text.insert(tk.INSERT, "{}\n".format(text1))
text.insert(tk.INSERT, text2)
text.tag_configure("highlight", background="grey")
text.tag_configure("normal", font=("Arial", 12))
text.tag_configure("large", font=("Arial", 18))
text.tag_add("normal", "1.0", "1.end")
text.tag_add("large", "2.0", "2.end")
text.tag_bind("normal", "<Enter>", lambda event, n = 1: highlight(n))
text.tag_bind("normal", "<Leave>", lambda event, n=1: remove_highlight(n))
text.tag_bind("large", "<Enter>", lambda event, n = 2: highlight(n))
text.tag_bind("large", "<Leave>", lambda event, n=2: remove_highlight(n))
text.configure(state="disabled")
root.mainloop()
解决方案
您的突出显示需要包含换行符才能跨越小部件的整个宽度。将“+1c”(加一个字符)添加到您的第二个索引:
text.tag_add("highlight", "{}.0".format(n), "{}.end+1c".format(n))
推荐阅读
- laravel - CSRF 令牌与 laravel 和 pusher 不匹配
- c - 我们如何在c中调用汇编函数?
- kotlin - kotlin 循环遍历 2 个不同长度的列表
- monaco-editor - 在光标位置访问类型定义?
- c# - 如何使用键作为内部列表中的项目初始化字典?
- python - 我有一些事件的实例和该事件的票证实例如何将所有创建的票证实例添加到事件实例列表
- gatsby - 使用 createPage 将组件传递到页面上下文
- terraform - terraform 执行计划中的前缀有什么区别?
- javascript - Javascript else if 语句意外停止执行
- azure - 在 Azure 数据工厂中保存触发器参数以更新插入最近修改的行