【问题标题】:Drag window handle for Tkinter?拖动 Tkinter 的窗口句柄?
【发布时间】:2011-09-17 14:46:17
【问题描述】:

首先,这是我当前的代码,它的重要部分:

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 的新手。任何帮助表示赞赏:) 重写课程是可以的,我知道它写得很糟糕。

【问题讨论】:

  • 我需要帮助才能将其变为现实,这基本上意味着类似课程的简化示例,因为我的 Python 技能似乎还不够广泛。
  • 这段代码看起来像是从这个答案复制过来的:stackoverflow.com/a/4055612/7432

标签: python drag-and-drop tkinter python-2.7


【解决方案1】:

这是一个小例子:

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_thislookLikeThis
  • 变量不需要声明。如果您想创建实例变量,请在 __init__ 中创建(绝对不要在方法之外,除非您需要类变量)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2013-11-11
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多