- 1 year ago
How to show window contents while dragging with python
To show window contents while dragging in Python, you can make use of a GUI framework like Tkinter. Tkinter provides a Toplevel
widget that allows you to create draggable windows. Here's an example of how you can achieve this:
pythonimport tkinter as tk
def drag_start(event):
root.x = event.x
root.y = event.y
def drag_motion(event):
deltax = event.x - root.x
deltay = event.y - root.y
root.geometry(f"+{root.winfo_x() + deltax}+{root.winfo_y() + deltay}")
root = tk.Tk()
root.title("Draggable Window")
# Make the window draggable
root.overrideredirect(True)
# Create a frame to hold the window contents
frame = tk.Frame(root, bg="white")
frame.pack(fill="both", expand=True)
# Add some contents to the frame
label = tk.Label(frame, text="Drag me!", font=("Helvetica", 16))
label.pack(padx=20, pady=20)
# Bind mouse events to the frame for dragging
frame.bind("<ButtonPress-1>", drag_start)
frame.bind("<B1-Motion>", drag_motion)
root.mainloop()
In this example, we create a window using Tk()
from Tkinter. We set the overrideredirect
flag to True
to remove the default window decorations (title bar, borders). We then create a frame inside the window to hold the window contents (in this case, a label).
Next, we bind the <ButtonPress-1>
event to the drag_start
function, which saves the initial mouse position when the left mouse button is pressed. We also bind the <B1-Motion>
event to the drag_motion
function, which calculates the delta movement of the mouse and updates the window's position accordingly.
When you run this script, you should see a draggable window with the label "Drag me!". You can click and drag anywhere inside the window to move it around the screen while the contents remain visible.