如何使用feedparser在tkinter文本小部件中添加文本链接? [英] How to add a link to text in tkinter text widget with feedparser?
本文介绍了如何使用feedparser在tkinter文本小部件中添加文本链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想构建一个简单的rss阅读器.我使用以下代码:
I would like to build a simple rss reader. I use the following code:
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()
绑定仅将最后一个链接附加到所有文本.我如何遍历链接并将其绑定到每个标题-完全有可能吗?我认为不是,因为最后只有一个文本,对吗?任何想法吗?
The bind only attachs the last link to all text. How can I iterate through the links and bind them to each headline - is this possible at all? I assume not, as it is one text in the end, right? Anyone any ideas?
推荐答案
您需要使用 tag_bind()
而不是 bind()
,因为 bind()
是基于窗口小部件的:
You need to use tag_bind()
instead of bind()
because bind()
is widget-wise:
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
这篇关于如何使用feedparser在tkinter文本小部件中添加文本链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文