Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

python - How can I add hyperlinks to a tkinter Text() widget?

I am working on a program that scrapes the top ten articles from news.ycombinator.com

Everything works the way I want it too now but I'd like to add hyperlinks to all of the links that show up in my tkinter Text() widget.

How can I add hyperlinks for each "link" I scraped?

screenshot of tkinter window

Scraper

import requests
from bs4 import BeautifulSoup
import hn_gui

res = requests.get(f'https://news.ycombinator.com/news')
soup = BeautifulSoup(res.text, 'html.parser')
links = soup.select('.storylink')
subtext = soup.select('.subtext')


def sort_stories_by_votes(hnlist):
    return sorted(hnlist, key=lambda k: k['votes'], reverse=True)


def create_custom_hn(links, subtext):
    hn = []
    for idx, item in enumerate(links):
        title = item.getText()
        href = item.get('href', None)
        vote = subtext[idx].select('.score')
        if len(vote):
            points = int(vote[0].getText().replace(' points', ''))
            if points > 99:
                hn.append({'title': title, 'link': href, 'votes': points})
    return sort_stories_by_votes(hn)


news = create_custom_hn(links, subtext)

hn_gui

Tkinter

from tkinter import *
from scraper import news

root = Tk()
root.title("Hacker News Top Ten")
text = Text(root, font=('Arial', 20), wrap="word")

for article in news:
    link = '{0} {1}'.format("Link:", article['link'])
    title = '{0} {1}'.format("
Title:", article['title'])
    votes = '{0} {1}'.format("
Votes:", article['votes'])
    text.insert(INSERT, link)
    text.insert(INSERT, title)
    text.insert(INSERT, votes)
    text.insert(END, "

")
text.config(bg="black", fg="grey")
text.pack(fill=BOTH, expand=1)

root.mainloop()
question from:https://stackoverflow.com/questions/65907467/how-can-i-add-hyperlinks-to-a-tkinter-text-widget

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

based on suggestion by @suraj_s here is your solution. I also merged two files into one

from tkinter import *
import requests, webbrowser
from bs4 import BeautifulSoup

res = requests.get(f'https://news.ycombinator.com/news')
soup = BeautifulSoup(res.text, 'html.parser')
links = soup.select('.storylink')
subtext = soup.select('.subtext')

def sort_stories_by_votes(hnlist):
    return sorted(hnlist, key=lambda k: k['votes'], reverse=True)

def create_custom_hn(links, subtext):
    hn = []
    for idx, item in enumerate(links):
        title = item.getText()
        href = item.get('href', None)
        vote = subtext[idx].select('.score')
        if len(vote):
            points = int(vote[0].getText().replace(' points', ''))
            if points > 99:
                hn.append({'title': title, 'link': href, 'votes': points})
    return sort_stories_by_votes(hn)


news = create_custom_hn(links, subtext)
#-------------------------------------------------
def callback(url):
    webbrowser.open_new(url)
    
root = Tk()
root.title("Hacker News Top Ten")
i = 0
for article in news:
    lbl = Label(root, text="Title: ")
    lbl.grid(row=i,column=0)
    lbl = Label(root, text=article['title'], fg="blue", cursor="hand2")
    lbl.grid(row=i,column=1)
    lbl.bind("<Button-1>", lambda e,url=article['link']: callback(url))
    lbl = Label(root, text="Votes: " + str(article['votes']))
    lbl.grid(row=i+1,column=0)
    i += 2

root.mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...