Drag window handle for Tkinter?

First of all, this is my current code, its essential parts:

class WindowDraggable(): x = 1 y = 1 def __init__(self,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): deltaX = event.x - self.x deltaY = event.y - self.y self.x = root.winfo_x() + deltaX self.y = root.winfo_y() + deltaY root.geometry("+%sx+%s" % (self.x,self.y)) #root is my window: root = Tk() #This is how I assign the class to label WindowDraggable(label) #All imports from Tkinter import * from PIL import Image, ImageTk import sys import re 

What I'm trying to do; Make the window a draggable handle, in this case label . I can’t describe how he is behaving now, but he moves the window without just following the mouse.

Please carry me since I'm new to Python. Any help is appreciated :) Rewriting the class is fine, I know this is really poorly written.

+1
source share
1 answer

Here is a small example:

 from Tkinter import * root = Tk() 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)) label = Label(root, text='drag me') WindowDraggable(label) label.pack() root.mainloop() 

This was almost correct for you, but you must compensate for the offset within the label itself. Please note that my example does not compensate for the border of the window. You will have to use certain tools to figure this out (so this example works fine when using overrideredirect(1) .

I assume that you come from a different programming language, so I will give you some tips while I am:

  • Python does not end statements with ; (while valid syntax, there is no reason for this).
  • Method names must either look_like_this sequentially or lookLikeThis .
  • Variables must not be declared. If you want to create an instance variable, do it in __init__ (and definitely not outside the method unless you want a class variable).
+2
source

All Articles