Home > front end >  how can i get rid of jumping while moving window on the button?
how can i get rid of jumping while moving window on the button?

Time:01-14

When i try to drag window with buttons, its jumping to the side of window. here is part of my code:

import webbrowser
import tkinter as tk
import tkinter.font as tkFont

class WindowDraggable():

    def __init__(self, label):
        self.label = label
        label.bind('<ButtonPress-1>', self.StartMove)
        label.bind('<ButtonRelease-1>', self.StopMove)
        label.bind('<B1-Motion>', self.OnMotion)

    def StartMove(self, event):
        self.x = event.x
        self.y = event.y

    def StopMove(self, event):
        self.x = None
        self.y = None

    def OnMotion(self,event):
        x = (event.x_root - self.x - self.label.winfo_rootx()   self.label.winfo_rootx())
        y = (event.y_root - self.y - self.label.winfo_rooty()   self.label.winfo_rooty())
        root.geometry(" %s %s" % (x, y))

How can i attach my full code here, because it says that my question is mostly code?

CodePudding user response:

Fixed the class:

class WindowDraggable:
    def __init__(self, window):
        self.window.bind("<Button-1>", self.start_move)
        self.window.bind("<B1-Motion>", self.on_motion)

    def start_move(self, event):
        self.offsetx = self.window.winfo_pointerx() - self.window.winfo_rootx()
        self.offsety = self.window.winfo_pointery() - self.window.winfo_rooty()

    def on_motion(self,event):
        x = self.window.winfo_pointerx() - self.offsetx
        y = self.window.winfo_pointery() - self.offsety
        self.window.geometry(f" {x} {y}")

I store the x and y offsets of the mouse with respect to the window's top left corner. Then I use the offset to calculate the new x and y coords of the window. For more info look here (the second piece of code is the one you should look at).

  • Related