Search code examples
pythontkinterbuttonmouseover

Show button in Tkinter when mouse is over window


I am having problems with showing a button when mouse is over a window. When I go over the window, the button shows up. But when I go over the button, it hides again. However, when I tried to recreate the problem with a simple program, it works fine... But something else bugs me in the short version.

import Tkinter as TK

root = TK.Tk()
root.geometry("400x300")
root.overrideredirect(True)

button = TK.Button(root, text = "HI", command = lambda: root.destroy())

def Show(event):
    button.place(x = 0, y = 0, width = 60, height = 30)

def Hide(event):
    button.place_forget()

root.bind("<Enter>", Show)
root.bind("<Leave>", Hide)

root.mainloop()

This short version works. But when you go over the button and then away from it, it hides. Even though you are still above the root window. Is there any easy way of forcing the button to be visible all the time the mouse si over the root? Thanks


Solution

  • You can check whether your mouse event was outside or inside the root frame and act accordingly

    def Hide(event):
        x, y = event.x, event.y
        x_r, y_r = root.winfo_x(), root.winfo_y()
        if x > x_r + root.winfo_width() or x < x_r or y > y_r + root.winfo_height() or y < y_r:
            button.place_forget()