赞
踩
First of all, this is my current code, essential parts of it:
class WindowDraggable():
x = 1
y = 1
def __init__(self,label):
label.bind('',self.StartMove);
label.bind('',self.StopMove);
label.bind('',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 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('', self.StartMove)
label.bind('', self.StopMove)
label.bind('', 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 or lookLikeThis.
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).
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。