簡體   English   中英

如何向 tkinter Text() 小部件添加超鏈接?

[英]How can I add hyperlinks to a tkinter Text() widget?

我正在開發一個程序,該程序從 news.ycombinator.com 中抓取前十篇文章

現在一切都按我想要的方式工作,但我想為我的 tkinter Text() 小部件中顯示的所有鏈接添加超鏈接。

如何為我抓取的每個“鏈接”添加超鏈接?

tkinter window 的屏幕截圖

刮刀

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("\nTitle:", article['title'])
    votes = '{0} {1}'.format("\nVotes:", article['votes'])
    text.insert(INSERT, link)
    text.insert(INSERT, title)
    text.insert(INSERT, votes)
    text.insert(END, "\n\n")
text.config(bg="black", fg="grey")
text.pack(fill=BOTH, expand=1)

root.mainloop()

根據@suraj_s 的建議,這是您的解決方案。 我還將兩個文件合並為一個

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM