所以我正在尝试 tkinter Text 小部件..并制作了一个小代码来突出显示文本中的“print”一词..代码:
from tkinter import *
def get(*arg):
print("Highlighting...")
text.tag_remove('found', '1.0', END)
s = "print"
if s:
idx = '1.0'
while 1:
idx = text.search(s, idx, nocase=1, stopindex=END)
if not idx: break
lastidx = '%s+%dc' % (idx, len(s))
text.tag_add('found', idx, lastidx)
idx = lastidx
text.see(idx) # Once found, the scrollbar automatically scrolls to the text
text.bind('<<Modified>>', get)
break
text.tag_config('found', foreground='green')
root = Tk()
text = Text(root)
text.grid()
root.bind('<<Modified>>', get)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
在此,root.bind('<<Modified>>', get)
作品仅一次。我用它只工作了一次的行检查了它,print("Highlighting...")
即使我输入了数千个字符..
难道我做错了什么?或者我的方法不好?
SPECS:
OS: Windows 7 SP1 (i will upgrade only to windows 11)
Python: Python 3.8.10
Arch: Intel x86
Run Code Online (Sandbox Code Playgroud)
在优秀的New Mexico Tech Tkinter 8.5 参考中找到了一种更简单的方法,您可以使用该方法重置修改后的标志.edit_modified()
。参见示例:
import tkinter as tk
root = tk.Tk()
textbox = tk.Text(root, width=30, height=15, padx=10, pady=5, wrap='word')
textbox.pack(pady=10, padx=10)
# Bind changes in textbox to callback function.
def modify_callback(event):
print('modify_callback')
textbox.edit_modified(False) # Reset the modified flag for text widget.
textbox.bind('<<Modified>>', modify_callback)
# Insert text, modifies text widget.
textbox.insert('end', 'Example text.')
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
由于某种原因,modify_callback()
文本小部件中的每次更改都会调用该函数两次,但我不知道为什么。
参考文献中的描述:
.edit_modified(arg=None)
Run Code Online (Sandbox Code Playgroud)
查询、设置或清除修改标志。该标志用于跟踪小部件的内容是否已更改。例如,如果您在文本小部件中实现文本编辑器,则可以使用修改的标志来确定自上次将内容保存到文件以来内容是否已更改。
当不带参数调用时,如果已设置修改标志,则此方法返回 True;如果清除,则返回 False。您还可以通过向此方法传递 True 值来显式设置修改标志,或通过传递 False 值来清除它。
任何插入或删除文本的操作,无论是通过程序操作还是用户操作,或者撤消或重做操作,都将设置修改标志。