Drag window handle for Tkinter?
First of all, this is my current code, essential parts of it:
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 am trying to accomplish is; Make the window draggable by 开发者_JAVA技巧a handle, in this case label
. I can't really describe how it behaves now, but it does move the window, simply not following the mouse.
Please bear with me as I am a total newcomer to Python. Any help is appreciated :) A rewrite of the class is okay, I know it's really badly written.
Here's a little 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()
You had it almost right, but you have to compensate for the offset within the label itself. Note that my example does not compensate for the window border. You will have to use of specific tools to figure that out (so this example works perfectly when using overrideredirect(1)
.
My guess is you're coming from another programming language, so I'll give you some tips while I'm at it:
- Python does not end statements with a
;
(while valid syntax, there is no reason to do it). - Method names should either consistently
look_like_this
orlookLikeThis
. - Variables do not need to be declared. If you want to create an instance variable do so in
__init__
(and definitely not outside a method unless you want a class variable).
精彩评论