python - 如何将超链接添加到 tkinter 按钮
问题描述
我目前正在处理 Tkinter 上的一些代码,我想知道它是否可能以及如何将网站超链接添加到按钮。就我而言,我正在尝试通过 Python 3 上的 Tkinter 将 Caldicot School 网址添加到按钮中,当单击它时,它会将您发送到那里
解决方案
欢迎来到 SO!
这个页面有一个用于创建一个按钮的方法,该按钮的作用类似于 tkinter http://code.activestate.com/recipes/580774-tkinter-link-or-hyperlink-button/中的超链接
代码的主要部分如下:
if __name__ == "__main__":
import webbrowser
try:
from Tkinter import Tk, Frame
except ImportError:
from tkinter import Tk, Frame
def callback():
webbrowser.open_new(r"http://www.google.com")
root = Tk()
frame = Frame(root, bg="white")
frame.pack(expand=True, fill="both")
# Creates a button that, when clicked, calls the function that sends you to your hyperlink.
link = Link_Button(frame, text="Google Hyperlink", action=callback)
link.pack(padx=10, pady=10)
root.mainloop()
检查上面的网站以获取类背后的代码Link_Button
。如果链接失效,下面是其余代码:
# Author: Miguel Martinez Lopez
try:
from Tkinter import Label
from ttk import Style
from tkFont import Font, nametofont
except ImportError:
from tkinter import Label
from tkinter.ttk import Style
from tkinter.font import Font, nametofont
def get_background_of_widget(widget):
try:
# We assume first tk widget
background = widget.cget("background")
except:
# Otherwise this is a ttk widget
style = widget.cget("style")
if style == "":
# if there is not style configuration option, default style is the same than widget class
style = widget.winfo_class()
background = Style().lookup(style, 'background')
return background
class Link_Button(Label, object):
def __init__(self, master, text, background=None, font=None, familiy=None, size=None, underline=True, visited_fg = "#551A8B", normal_fg = "#0000EE", visited=False, action=None):
self._visited_fg = visited_fg
self._normal_fg = normal_fg
if visited:
fg = self._visited_fg
else:
fg = self._normal_fg
if font is None:
default_font = nametofont("TkDefaultFont")
family = default_font.cget("family")
if size is None:
size = default_font.cget("size")
font = Font(family=family, size=size, underline=underline)
Label.__init__(self, master, text=text, fg=fg, cursor="hand2", font=font)
if background is None:
background = get_background_of_widget(master)
self.configure(background=background)
self._visited = visited
self._action = action
self.bind("<Button-1>", self._on_click)
@property
def visited(self):
return self._visited
@visited.setter
def visited(self, is_visited):
if is_visited:
self.configure(fg=self._visited_fg)
self._visited = True
else:
self.configure(fg=self._normal_fg)
self._visited = False
def _on_click(self, event):
if not self._visited:
self.configure(fg=self._visited_fg)
self._visited = True
if self._action:
self._action()
推荐阅读
- python - 有没有办法在python中安装包后下载包资源?
- mysql - mysql的日期时间值不正确
- java - 扫描仪使用循环从命令行读取文本文件,但循环不会中断
- python - django 创建客户端用户
- excel - 将粘贴值和格式从一张表复制到另一张表时出现 VBA 错误 1004
- asp.net - Hangfire:看起来工作被中止了
- php - 在 Mac 上为 Laravel 7 / Homestead 更新 PHP 到 7.2.5
- webpack - Webpack 需要一个合适的加载器来处理这个文件类型错误
- python - 我的数据库已经有 20 行,但是当我保存新行时,它们的 id 从 1 开始
- django - 如何告诉我的序列化程序可以将字段留空?