0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python Tkinter ツールチップ (マウスホバーでメッセージ表示)

Posted at

image.png

import tkinter as tk

class ToolTip:
    def __init__(self, widget, text):
        self.widget = widget
        self.text = text
        self.tooltip_window = None

        self.widget.bind("<Enter>", self.show_tooltip)
        self.widget.bind("<Leave>", self.hide_tooltip)

    def show_tooltip(self, event):
        if self.tooltip_window or not self.text:
            return

        x, y, _, _ = self.widget.bbox("insert")
        x += self.widget.winfo_rootx() + 25
        y += self.widget.winfo_rooty() + 25

        self.tooltip_window = tw = tk.Toplevel(self.widget)
        tw.wm_overrideredirect(True)
        tw.wm_geometry(f"+{x}+{y}")

        label = tk.Label(tw, text=self.text, justify='left',
                         background='#ffffe0', relief='solid', borderwidth=1,
                         font=("tahoma", "8", "normal"))
        label.pack(ipadx=1)

    def hide_tooltip(self, event):
        if self.tooltip_window:
            self.tooltip_window.destroy()
            self.tooltip_window = None

root = tk.Tk()
root.title("Tkinter Tooltip Example")


#--------------------
# label ウィジェットを作成
label1 = tk.Label(root, text="ツールチップ例 ここにマウスカーソルを合わせるとメッセージが表示されます")
label1.pack(pady=10, padx=10)

# labelにツールチップを設定
ToolTip(label1, "ツールチップの例です")

#--------------------
# Entry ウィジェットを作成
entry1 = tk.Entry(root)
entry1.pack(pady=10, padx=10)

# Entry1にツールチップを設定
ToolTip(entry1, "ここにテキストを入力してください")


#--------------------
root.mainloop()

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?