拖动窗口手柄?

2024-10-01 17:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,这是我当前的代码,它的基本部分:

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

我要实现的是:使窗口可以通过句柄拖动,在本例中是label。我现在无法真正描述它的行为,但它确实移动了窗口,只是没有跟随鼠标。在

请原谅我,因为我是Python的新手。任何帮助都是感激的:)重写这个类是可以的,我知道它写得很糟糕。在


Tags: importselfnoneeventbinddefrootlabel
1条回答
网友
1楼 · 发布于 2024-10-01 17:26:52

下面是一个小例子:

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

你几乎是对的,但是你必须补偿标签本身的偏移量。请注意,我的示例没有补偿窗口边框。您必须使用特定的工具来解决这一问题(因此,当使用overrideredirect(1)时,这个示例可以完美地工作。在

我猜你是从另一种编程语言来的,所以我在学习的时候给你一些提示:

  • Python不以;结束语句(虽然语法有效,但没有理由这么做)。在
  • 方法名应该一致look_like_this或{}。在
  • 不需要声明变量。如果要创建实例变量,请在__init__中创建实例变量(除非需要类变量,否则绝对不要在方法外部创建)。在

相关问题 更多 >

    热门问题