如何在Tkinter中使用标签创建超链接?

29

如何在Tkinter中使用Label创建超链接?

快速搜索并没有显示如何做到这一点。相反,只有在一个Text小部件中创建超链接的解决方案。

7个回答

56

将标签绑定到"<Button-1>"事件。当该事件被触发时,回调函数会被执行,从而在您的默认浏览器中打开一个新页面。

from tkinter import *
import webbrowser

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

root = Tk()
link1 = Label(root, text="Google Hyperlink", fg="blue", cursor="hand2")
link1.pack()
link1.bind("<Button-1>", lambda e: callback("http://www.google.com"))

link2 = Label(root, text="Ecosia Hyperlink", fg="blue", cursor="hand2")
link2.pack()
link2.bind("<Button-1>", lambda e: callback("http://www.ecosia.org"))

root.mainloop()

您也可以通过更改回调来打开文件:

webbrowser.open_new(r"file://c:\test\test.csv")

1
Peregrinius,open_new参数中的'r'是什么意思? - Ecko
3
这会把字符串文字化,因此您不必转义反斜杠。 - James Burke
@JamesBurke 如果你有两个标签想要做链接,你如何应用这个解决方案? - fractalflame
也许我有点儿挑剔,但更符合tkinter方式的做法是在pack()之前将函数绑定到标签上。 - Lukkar
1
绑定到 "<ButtonRelease-1>" 不是更好吗? - TheLizzard

11

如果您有多个标签并希望将其全部用于一个函数,则可以选择另一种方法。这是在假设链接为文本的情况下。

import tkinter as tk
import webbrowser

def callback(event):
    webbrowser.open_new(event.widget.cget("text"))

root = tk.Tk()
lbl = tk.Label(root, text=r"http://www.google.com", fg="blue", cursor="hand2")
lbl.pack()
lbl.bind("<Button-1>", callback)
root.mainloop()

绑定到 "<ButtonRelease-1>" 不是更好吗? - TheLizzard

4

有一个名为tkhtmlview的PyPi模块(pip install tkhtmlview),支持在tkinter中使用HTML。它仅支持某些标记,但在页面上,它声称完全支持超链接的锚标记(anchor tags)以及支持href属性。它需要Python 3.4或更高版本与tcl/tk(tkinter)支持以及Pillow 5.3.0模块。我还没有尝试过<img>标签,但我已经尝试了该模块并且有效。

例如:

import tkinter as tk
from tkhtmlview import HTMLLabel

root = tk.Tk()
html_label=HTMLLabel(root, html='<a href="http://www.google.com"> Google Hyperlink </a>')
html_label.pack()
root.mainloop()

3

你可以简单地导入webbrowser,添加一个函数并在按钮内调用它。声明您的布局管理器。以下是代码的样子:

from tkinter import *
import webbrowser

# Displaying the root window
window = Tk()
window.config(padx=100, pady=100)


# Function Declaration
def callback():
    webbrowser.open_new("https://www.google.com/")


# Button Declaration
your_variable_name = Button(text="button_name", command=callback)
your_variable_name.grid(column=2, row=3)

# keeping the Tkinter Interface running
window.mainloop()

提醒:它会在计算机的默认浏览器中打开。


0
""" Hyperlink *with* hover affect - Wallee """

from tkinter import *
import webbrowser


# Creates hyperlinks
def hyperlink(root, link: str, **kwargs) -> Label:

    # Iterate through a few default settings to make it look like a link
    for i in (("fg", "blue"), ("text", "Hyperlink!"), ("font", "None 10"), ("cursor", "hand2")):
        kwargs.setdefault(i[0], i[1])

    # Create the label
    label = Label(root, **kwargs)
    label.link = link

    # Bind the click event to a lambda that opens the link using the webbrowser module
    label.bind("<Button-1>", lambda e: webbrowser.open(e.widget.link))

    # Bind the enter and leave events to add a hover affect
    label.bind("<Enter>", lambda e: e.widget.configure(font=e.widget.cget("font") + " underline"))
    label.bind("<Leave>", lambda e: e.widget.configure(font=e.widget.cget("font")[:-10]))

    return label

# Basic Tkinter setup
root = Tk()
root.geometry("150x50")

# Create and pack the "hyperlink" (AKA label)
link = hyperlink(root, "https://www.google.com", font="None 15")
link.pack()

root.mainloop()

0
你可以创建一个继承自tkinter模块的label小部件的类,用额外的值进行初始化,包括课程的链接... 然后按照下面的示例创建一个实例。
import tkinter as t
import webbrowser


class Link(t.Label):
    
    def __init__(self, master=None, link=None, fg='grey', font=('Arial', 10), *args, **kwargs):
        super().__init__(master, *args, **kwargs)
        self.master = master
        self.default_color = fg # keeping track of the default color 
        self.color = 'blue'   # the color of the link after hovering over it 
        self.default_font = font    # keeping track of the default font
        self.link = link 

        """ setting the fonts as assigned by the user or by the init function  """
        self['fg'] = fg
        self['font'] = font 

        """ Assigning the events to private functions of the class """

        self.bind('<Enter>', self._mouse_on)    # hovering over 
        self.bind('<Leave>', self._mouse_out)   # away from the link
        self.bind('<Button-1>', self._callback) # clicking the link

    def _mouse_on(self, *args):
        """ 
            if mouse on the link then we must give it the blue color and an 
            underline font to look like a normal link
        """
        self['fg'] = self.color
        self['font'] = self.default_font + ('underline', )

    def _mouse_out(self, *args):
        """ 
            if mouse goes away from our link we must reassign 
            the default color and font we kept track of   
        """
        self['fg'] = self.default_color
        self['font'] = self.default_font

    def _callback(self, *args):
        webbrowser.open_new(self.link)  


root = t.Tk()
root.title('Tkinter Links !')
root.geometry('300x200')
root.configure(background='LightBlue')

URL = 'www.python.org'

link = Link(root, URL, font=('sans-serif', 20), text='Python', bg='LightBlue')
link.pack(pady=50)

root.mainloop()

0
from tkinter import *
import tkinter as tkr
import webbrowser


link = Label(root, text="Forgot your password?", fg="blue", cursor="hand2")
link.grid(row=4,column=3)
link.bind("<Button-1>", lambda e: webbrowser.open_new_tab("https://thozhiindia.com/login?forget_password")

)

1
你的回答可以通过提供更多支持性信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人能够确认你的回答是否正确。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接