如何使用 feedparser 在 tkinter 文本小部件中向文本添加 link?

How to add a link to text in tkinter text widget with feedparser?

我想构建一个简单的 rss reader。我使用以下代码:

import tkinter as tk
import feedparser
import sqlite3
import webbrowser
NewsFeed = feedparser.parse("https://www.wired.com/feed/rss")

i = 0

def callback(url):
    webbrowser.open_new(url)

def output():

   for i in range(40):
        entry = NewsFeed.entries[i]
        textInput.tag_config("a",  foreground="black")
        textInput.insert(tk.END,  entry.title + "\n\n", "a")
        textInput.insert(tk.END,  entry.summary + "\n\n", "b")
        textInput.bind("<1>", lambda e: callback(entry.link))

root = tk.Tk()
root.geometry("710x640")
root.configure(bg='white')
root.title("RSS Reader")

scroll = tk.Scrollbar(root)
scroll.grid(row=1, column=1, rowspan=50, sticky='ns')

padybutton=3
photo1=tk.PhotoImage(file="ico/button.gif")

textInput=tk.Text(root, width=50, height=37)
textInput.grid(row=0, column=0, rowspan=50, padx=10, pady=10)
textInput.configure(yscrollcommand=scroll.set, wrap=tk.WORD)
scroll.configure(command=textInput.yview)
#photo1=tk.PhotoImage(file="ico/button.gif")

btnRead=tk.Button(root, height=1, width=10, text="Check", command=output)
btnRead.config(image=photo1, text="Update", compound="center", width="120",height="20",borderwidth="0", font=('Verdana', 10), fg='#FFFFFF')
btnRead.grid(row=2, column=3, sticky=tk.N, padx=padybutton, pady=padybutton)

root.mainloop()

绑定仅将最后一个 link 附加到所有文本。我如何遍历 link 并将它们绑定到每个标题 - 这可能吗?我假设不是,因为它最终是一个文本,对吗?有人有什么想法吗?

您需要使用 tag_bind() 而不是 bind() 因为 bind() 是小部件方面的:

def output():
   for i in range(40):
        entry = NewsFeed.entries[i]
        textInput.tag_config("a",  foreground="black")
        # str(i) is used in tag_bind() and "a" can be used for showing the link in underline
        textInput.insert(tk.END,  entry.title + "\n\n", ("a", str(i))) 
        textInput.insert(tk.END,  entry.summary + "\n\n", "b")
        textInput.tag_bind(str(i), "<1>", lambda e, url=entry.link: callback(url))

...

textInput.tag_configure("a", underline=True) # show link with underline