展示效果
全部代码和使用示例
python">
import tkinter as tk
import pyautoguiscreen_width, screen_height = pyautogui.size()class WidgetTip:"""鼠标悬停提示"""def __init__(self, widget, text):self.widget = widgetself.text = textself.tips_alpha = 1self.tooltip = tk.StringVar()self.tip_pos = 5self.tooltip_window = tk.Toplevel()self.init_tips()self.widget.bind("<Enter>", self.enter)self.widget.bind("<Motion>", self.move)self.widget.bind("<Leave>", self.leave)def init_tips(self):"""初始化消息框"""self.tooltip_window.attributes("-alpha", 0)self.tooltip_window.attributes("-toolwindow", 1)self.tooltip_window.wm_overrideredirect(True)self.tooltip_window.attributes('-topmost', 100)pad_x = 20 tk.Label(self.tooltip_window,textvariable=self.tooltip,background="#ffffff",justify=tk.LEFT,relief="solid",borderwidth=0,wraplength=screen_width - pad_x,padx=pad_x, pady=10).pack()def enter(self, event=None):self.tooltip_window.lift()if isinstance(self.text, (tk.StringVar, tk.IntVar, tk.BooleanVar, tk.DoubleVar)):tips_text = str(self.text.get())else:tips_text = str(self.text)self.tooltip.set(tips_text)self.set_tooltip_window_geometry(event)self.tooltip_window.attributes("-alpha", self.tips_alpha)def move(self, event=None):self.set_tooltip_window_geometry(event)def leave(self, event=None):self.tooltip_window.attributes("-alpha", 0)self.set_tooltip_window_geometry(event)def set_tooltip_window_geometry(self, event):cost_length = event.x_root + self.tip_pos + self.tooltip_window.winfo_width() - screen_widthif cost_length < 0:cost_length = 0self.tooltip_window.geometry("+%d+%d" % (event.x_root + self.tip_pos - cost_length, event.y_root + self.tip_pos))
root = tk.Tk()
root.title("鼠标悬停提示")var_str = tk.StringVar()
button = tk.Button(root, text="鼠标放这")
button.pack(pady=20)var_str.set('动态文本按钮')button2 = tk.Button(root, text=var_str.get())
button2.pack(pady=20)var_str.set('这是一条动态文本提示语')WidgetTip(button, "这是一条提示鼠标悬停提示信息")
WidgetTip(button2, var_str)
root.mainloop()