当前位置:   article > 正文

tkinter python 句柄_拖动Tkinter的窗口句柄?

tkinter motion拖动窗口

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).

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/892353
推荐阅读
相关标签
  

闽ICP备14008679号