首先要对 Text 小部件的某些部分应用格式,您需要了解 tags,在大多数情况下,您可能只需使用链接的短语 (ABC123),请记住:
标签的名称可以是任何不包含空格或句点的字符串。
一旦你有一个链接标签,有两个部分:
- 格式化标签,使其看起来和反应像一个链接。
- 将标签应用于文本中的短语。
第一个非常简单,如果您只是希望它是蓝色并带有下划线并响应被点击:
def format_link(text_widget,tag,command):
text_widget.tag_config(tag,foreground="blue",underline=1)
text_widget.tag_bind(tag,"<Button-1>",command)#remember that the command will need to take an event argument
虽然如果您希望光标在悬停时更改或在单击后更改颜色等,这可能会变得更加复杂。
第二部分是将此标记应用于文本自动,我假设这意味着在将文本插入小部件后对其进行解析。这也很简单,只需将this answer 放入一个循环中,以便检查每个出现的短语:
def apply_tag(text_widget,phrase,tag,regexp=False):
countVar = tk.IntVar(text_widge)
idx = "1.0"
while idx:
idx = text_widget.search(phrase,idx, stopindex = "end",
count = countVar, regexp = regexp)
if idx:
end_idx = "%s + %sc" %(idx, countVar.get())
text_widget.tag_add(tag, idx, end_idx)
idx = end_idx
剩下的就是定义在另一个程序中打开文件的方式,然后调用上面的两个函数,使用os.system("open"...)打开文件就可以这么简单:
def make_link(text,phrase,file_to_open):
def callback(event=None):
os.system("open %r"%file_to_open)#there are better ways of handling this
apply_tag(text,phrase,phrase)#uses phrase as tag
format_link(text,phrase,callback)
虽然您可能想查看 answers here 或 it's duplicate 以了解打开文件的替代方法。
在将文本插入小部件后,假设您有某种短语列表可以转换为链接,您可以遍历这些短语并为每个短语调用 make_link:
phrases = {"1931-125", "699-126", "1851-127"}
for s in phrases:
make_link(TEXT_W, s, s+".pdf") #make a link to same name with .pdf added to end.