Как добавить картинку во всплывающую подсказку (Hovertip)
Хочу сделать чтобы при наведении на кнопку выводилась картинка и под ней текст.
Вот кусок кода:
import tkinter as tk
from tkinter import *
import subprocess
import os
from tkinter import ttk
from idlelib.tooltip import Hovertip
root = tk.Tk()
root.title("Добро пожаловать в приложение PythonRu")
root.geometry('500x200')
tab = ttk.Notebook(root)
tab.grid(sticky='nsew')
tab1 = tk.Frame(tab, bg='black')
tab2 = tk.Frame(tab, bg='black')
tab3 = tk.Frame(tab, bg='black')
tab4 = tk.Frame(tab, bg='black')
tab5 = tk.Frame(tab, bg='black')
tab6 = tk.Frame(tab, bg='black')
# tab7 = tk.Frame(tab, bg='black')
tab8 = tk.Frame(tab, bg='black')
tab9 = tk.Frame(tab, bg='black')
tab10 = tk.Frame(tab, bg='black')
# tab11 = tk.Frame(tab, bg='black')
# tab12 = tk.Frame(tab, bg='black')
tab.add(tab1, text='Browser ')
tab.add(tab2, text='Сleaning ')
tab.add(tab3, text='InfoPC ')
tab.add(tab4, text='Editors ')
tab.add(tab5, text='Files ')
tab.add(tab6, text='Media ')
# tab.add(tab7, text='Adobe')
tab.add(tab8, text='Updates ')
tab.add(tab9, text='Adobe ')
tab.add(tab10, text='Utilities ')
# tab.add(tab11, text='Adobe')
# tab.add(tab12, text='Adobe')
def q():
subprocess.call(['SOURSE/BROWSER/ChromeS.exe'])
btn1 = Button(tab1, text="S", command=q, bg="#98795d", fg="White")
btn1.place(relx=0.035, rely=0.1, anchor="c", height=20, width=20, bordermode=OUTSIDE)
btn1 = Button(tab1, text="Chrome", bg="#98795d", fg="White")
btn1.place(relx=0.16, rely=0.1, anchor="c", height=20, width=90, bordermode=OUTSIDE)
btn1.config(command=lambda: subprocess.call(['SOURSE/BROWSER/Chrome.exe']))
H = Hovertip(btn1, "tooltip text", hover_delay=100)
def w():
subprocess.call(['SOURSE/BROWSER/FirefoxS.exe'])
btn1 = Button(tab1, text="S", command=w, bg="#98795d", fg="White")
btn1.place(relx=0.035, rely=0.26, anchor="c", height=20, width=20, bordermode=OUTSIDE)
btn1 = Button(tab1, text="Firefox", bg="#98795d", fg="White")
btn1.place(relx=0.16, rely=0.26, anchor="c", height=20, width=90, bordermode=OUTSIDE)
btn1.config(command=lambda: subprocess.call(['SOURSE/BROWSER/Firefox.exe']))
def e():
subprocess.call(['SOURSE/BROWSER/OperaS.exe'])
btn1 = Button(tab1, text="S", command=e, bg="#98795d", fg="White")
btn1.place(relx=0.035, rely=0.42, anchor="c", height=20, width=20, bordermode=OUTSIDE)
btn1 = Button(tab1, text="Opera", bg="#98795d", fg="White")
btn1.place(relx=0.16, rely=0.42, anchor="c", height=20, width=90, bordermode=OUTSIDE)
btn1.config(command=lambda: subprocess.call(['SOURSE/BROWSER/Opera.exe']))
def r():
subprocess.call(['SOURSE/BROWSER/OperaGXS.exe'])
btn1 = Button(tab1, text="S", command=r, bg="#98795d", fg="White")
btn1.place(relx=0.035, rely=0.58, anchor="c", height=20, width=20, bordermode=OUTSIDE)
btn1 = Button(tab1, text="Opera GX", bg="#98795d", fg="White")
btn1.place(relx=0.16, rely=0.58, anchor="c", height=20, width=90, bordermode=OUTSIDE)
btn1.config(command=lambda: subprocess.call(['SOURSE/BROWSER/OperaGX.exe']))
def t():
subprocess.call(['SOURSE/BROWSER/VivaldiS.exe'])
btn1 = Button(tab1, text="S", command=t, bg="#98795d", fg="White")
btn1.place(relx=0.035, rely=0.74, anchor="c", height=20, width=20, bordermode=OUTSIDE)
btn1 = Button(tab1, text="Vivaldi", bg="#98795d", fg="White")
btn1.place(relx=0.16, rely=0.74, anchor="c", height=20, width=90, bordermode=OUTSIDE)
btn1.config(command=lambda: subprocess.call(['SOURSE/BROWSER/Vivaldi.exe']))
def y():
subprocess.call(['SOURSE/BROWSER/YandexS.exe'])
btn1 = Button(tab1, text="S", command=y, bg="#98795d", fg="White")
btn1.place(relx=0.035, rely=0.9, anchor="c", height=20, width=20, bordermode=OUTSIDE)
btn1 = Button(tab1, text="Yandex", bg="#98795d", fg="White")
btn1.place(relx=0.16, rely=0.9, anchor="c", height=20, width=90, bordermode=OUTSIDE)
btn1.config(command=lambda: subprocess.call(['SOURSE/BROWSER/Yandex.exe']))
def l():
subprocess.call(['SOURSE/BROWSER/Edges.exe'])
btn1 = Button(tab1, text="S", command=l, bg="#98795d", fg="White")
btn1.place(relx=0.36, rely=0.1, anchor="c", height=20, width=20, bordermode=OUTSIDE)
btn1 = Button(tab1, text="Edge", bg="#98795d", fg="White")
btn1.place(relx=0.485, rely=0.1, anchor="c", height=20, width=90, bordermode=OUTSIDE)
btn1.config(command=lambda: subprocess.call(['SOURSE/BROWSER/Edge.exe']))
def z():
subprocess.call(['SOURSE/BROWSER/URANS.exe'])
btn1 = Button(tab1, text="S", command=z, bg="#98795d", fg="White")
btn1.place(relx=0.36, rely=0.26, anchor="c", height=20, width=20, bordermode=OUTSIDE)
btn1 = Button(tab1, text="URAN", bg="#98795d", fg="White")
btn1.place(relx=0.485, rely=0.26, anchor="c", height=20, width=90, bordermode=OUTSIDE)
btn1.config(command=lambda: subprocess.call(['SOURSE/BROWSER/URAN.exe']))
Ответы (1 шт):
Смотрим класс Hovertip в исходниках python:
class Hovertip(OnHoverTooltipBase):
"A tooltip that pops up when a mouse hovers over an anchor widget."
def __init__(self, anchor_widget, text, hover_delay=1000):
"""Create a text tooltip with a mouse hover delay.
anchor_widget: the widget next to which the tooltip will be shown
hover_delay: time to delay before showing the tooltip, in milliseconds
Note that a widget will only be shown when showtip() is called,
e.g. after hovering over the anchor widget with the mouse for enough
time.
"""
super(Hovertip, self).__init__(anchor_widget, hover_delay=hover_delay)
self.text = text
def showcontents(self):
label = Label(self.tipwindow, text=self.text, justify=LEFT,
background="#ffffe0", relief=SOLID, borderwidth=1)
label.pack()
Видим, что там вставляется Label с указанным текстом. В Label можно вставить картинку (объект PhotoImage) через параметр image, но в данной реализации Hovertip этот параметр в Label не получится передать. Поэтому делаем свою реализацию Hovertip, в которой в Label будут передаваться все именованные параметры (**kwargs), переданные при создании объекта.
Копипастим код класса Hovertip и модифицируем как нам нужно (можно было бы отнаследоваться от Hovertip, но тут нет особого смысла наследоваться от него, т.к. первоначальный код этого класса полностью заменяется):
import tkinter as tk
from idlelib.tooltip import OnHoverTooltipBase
class LabelHovertip(OnHoverTooltipBase):
def __init__(self, anchor_widget, hover_delay=1000, **kwargs):
super().__init__(anchor_widget, hover_delay=hover_delay)
self.kwargs = kwargs
def showcontents(self):
label = tk.Label(
self.tipwindow,
justify=tk.LEFT,
background="#ffffe0",
relief=tk.SOLID,
borderwidth=1,
**self.kwargs
)
label.pack()
root = tk.Tk()
bt1 = tk.Button(root, text="Text tooltip")
bt1.pack()
# При передаче параметра text будет работать как стандартный Hovertip
LabelHovertip(bt1, hover_delay=100, text="tooltip text")
bt2 = tk.Button(root, text="Image tooltip")
bt2.pack()
# При передаче параметра image в Label будет вставляться указанная картинка
img = tk.PhotoImage(file="some_image.png")
LabelHovertip(bt2, hover_delay=100, image=img, highlightthickness=2, highlightbackground="gray")
# highlightthickness=2, highlightbackground="gray" - для добавления серой рамки толщиной в 2 пикселя
# (эти параметры тоже передаются в Label)
root.mainloop()
Скриншоты:


