Python 如何在 Tkinter 中创建带有标签的超链接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23482748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a hyperlink with a Label in Tkinter?
提问by James Burke
How do you create a hyperlinkusing a Label
in Tkinter?
如何在 Tkinter 中使用 a创建超链接Label
?
A quick search did not reveal how to do this. Instead there were only solutions to create a hyperlink in a Text
widget.
快速搜索并没有揭示如何做到这一点。相反,只有在Text
小部件中创建超链接的解决方案。
采纳答案by James Burke
Bind the label to "<Button-1>"
event. When it is raised the callback
is executed resulting in a new page opening in your default browser.
将标签绑定到"<Button-1>"
事件。当它被引发时,callback
会在你的默认浏览器中打开一个新页面。
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()
You can also open files by changing the callback to:
您还可以通过将回调更改为:
webbrowser.open_new(r"file://c:\test\test.csv")
回答by Steven Summers
Alternatively if you have multiple labels and want the one function for all. That is assuming you have the link as the text
或者,如果您有多个标签并希望所有标签都具有一个功能。那是假设您将链接作为文本
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()
回答by Xbox One
There is a module on PyPi called tkhtmlview(pip install tkhtmlview
) that supports HTML in tkinter. It only supports some tags, but on the page, it says that it has full support fro tags (anchor tags for hyperlinks), and supports the href attribute. It requires Python 3.4 or later with tcl/tk (tkinter) support and the Pillow 5.3.0 module. I haven't tried the tag yet, but I tried the module in general and it works.
PyPi上有一个名为 tkhtmlview( pip install tkhtmlview
)的模块,它支持tkinter 中的HTML。它只支持一些标签,但在页面上,它说它完全支持标签(超链接的锚标签),并支持 href 属性。它需要具有 tcl/tk (tkinter) 支持和 Pillow 5.3.0 模块的 Python 3.4 或更高版本。我还没有尝试过这个标签,但是我总体上尝试了这个模块并且它可以工作。
As an example:
举个例子:
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()