python Tkinter have displayed text as hyperlink [d

2019-07-23 19:56发布

问题:

This question already has an answer here:

  • How to create a hyperlink with a Label in Tkinter? 2 answers

I am creating a simple search engine for my university site using Selenium and Tkinter. My code creates the GUI and produces URL links to queries entered into the search box. Is it possible to have these produced URLs as clickable hyperlinks within the GUI? If so, how would I go about doing this?

import selenium.webdriver as webdriver
from selenium.webdriver.chrome.options import Options
from tkinter import *



def get_results(search_term, num_results = 10):
    url = "https://www.startpage.com"
    options = Options()
    options.add_argument('--headless')
    options.add_argument('--disable-gpu')  
    chromedriver = "chromedriver.exe"
    args = ["hide_console", ]
    browser = webdriver.Chrome(chromedriver, service_args = args, options = 
options) 
    browser.get(url)
    browser.set_window_position(0, 0)
    browser.set_window_size(0, 0)
    search_box = browser.find_element_by_id("query")
    search_box.send_keys(search_term)
    search_box.submit()
    try:
        links = 
browser.find_elements_by_xpath("//ol[@class='web_regular_results']//h3//a")
    except:
        links = browser.find_elements_by_xpath("//h3//a")
    results = []
    for link in links[:num_results]:
        href = link.get_attribute("href")
        print(href)
        results.append(href)
        results.append(href)
        mlabel2 = Label(mGui, text = href).pack()
    browser.close()

    return results



def search_query():
    mtext = ment.get()
    user_search = get_results(mtext + " site:essex.ac.uk")

    return

response = get_results
mGui = Tk()
ment = StringVar()
mGui.geometry('640x640+0+0')
mGui.title('Essex University Search')
mlabel = Label(mGui, text = 'Essex University Search', font = ("arial", 40, 
"bold"), fg = "steelblue").pack()
mbutton = Button(mGui, text = 'Search', command = search_query, font = 
("arial", 10), fg = 'white', bg = 'steelblue').pack()
mEntry = Entry(mGui, textvariable = ment).pack()

回答1:

If you just want to make a whole Label look and work like a hyperlink, this is pretty easy. I'll just do a dumb webbrowser.open instead of talking to a webdriver, so this can run without any extra libraries or configuration.

from tkinter import *
import webbrowser

root = Tk()
link = Label(root, text="http://stackoverflow.com", fg="blue", cursor="hand2")
link.pack()
link.bind("<Button-1>", lambda event: webbrowser.open(link.cget("text")))
root.mainloop()

But if you want to embed hyperlinks in the middle of text within a Label, that's hard. There's no easy way to style part of a Label different from the rest. And when you get that <Button-1>, you have to manually figure out where in the string it hit. And I'm not aware of any libraries that wrap this up and make it easier.

If you're willing to use a Text instead of Label, on the other hand, the support is already there, and wrapping it up isn't that hard. Borrowing the Hyperlink Manager out of the tkinter book:

from functools import partial
from tkinter import *
import webbrowser
from tkHyperlinkManager import HyperlinkManager

root = Tk()
text = Text()
text.pack()
hyperlink = HyperlinkManager(text)
text.insert(INSERT, "Hello, ")
text.insert(INSERT, "Stack Overflow",
            hyperlink.add(partial(webbrowser.open, "http://stackoverflow.com")))
text.insert(INSERT, "!\n\n")
text.insert(INSERT, "And here's ")
text.insert(INSERT, "a search engine",
            hyperlink.add(partial(webbrowser.open, "http://duckduckgo.com")))
text.insert(INSERT, ".")

root.mainloop()

Of course you could wrap up the partial(webbrowser.open, url) in a method so you can just call hyperlink.add('http://stackoverflow.com'), or even wrap the text.insert in there so you can just call hyperlink.insert(INSERT, 'Stack Overflow', 'http://stackoverflow.com'), but I left the simple interface of tkHyperlinkManager alone to make it easier to understand what it's doing.

And as you can from the pretty short and simple tkHyperlinkManager code, what it's doing isn't all that difficult. You just wrap each hyperlink in a tag and insert that in place of the raw text, and you get the tag back with each event, so you can easily look up what you want to do for that specific tag.