Python/Tkinter:鼠标拖动没有边框的窗口,例如.overridedirect(1)

Mal*_*olm 3 python windows user-interface window tkinter

关于如何创建允许用户鼠标拖动没有边框的窗口的事件绑定的任何建议,例如.用overridedirect(1)创建的窗口?

使用案例:我们想创建一个浮动的工具栏/调色板窗口(没有边框),我们的用户可以在他们的桌面上拖动它们.

这就是我的想法(伪代码):

__PRE__

Tkinter是否暴露了足够的功能以允许我实现手头的任务?或者是否有更容易/更高级别的方法来实现我想要做的事情?

Bry*_*ley 10

是的,Tkinter公开了足够的功能来做到这一点,不,没有更容易/更高级的方法来实现你想做的事情.你几乎有正确的想法.

这是一个例子:

import Tkinter as tk
import tkFileDialog 

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.floater = FloatingWindow(self)

class FloatingWindow(tk.Toplevel):
    def __init__(self, *args, **kwargs):
        tk.Toplevel.__init__(self, *args, **kwargs)
        self.overrideredirect(True)

        self.label = tk.Label(self, text="Click on the grip to move")
        self.grip = tk.Label(self, bitmap="gray25")
        self.grip.pack(side="left", fill="y")
        self.label.pack(side="right", fill="both", expand=True)

        self.grip.bind("<ButtonPress-1>", self.StartMove)
        self.grip.bind("<ButtonRelease-1>", self.StopMove)
        self.grip.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
        x = self.winfo_x() + deltax
        y = self.winfo_y() + deltay
        self.geometry("+%s+%s" % (x, y))



app=App()
app.mainloop()
Run Code Online (Sandbox Code Playgroud)

  • 布莱恩!非常感谢您的帮助。多么酷的功能 - 我将拥有许多利用此功能的有趣构建工具。我也很喜欢你创造抓地力的技巧——非常聪明。对于关注此线程的读者,我在“self.overrideredirect(True)”行之后添加了“self.attributes('-topmost', 1)”行,以使 Bryan 的浮动窗口显示在所有窗口的顶部。我认为这展示了人们如何使用 Bryan 的解决方案来创建各种桌面实用程序的潜力。 (3认同)
  • 我想隐藏主窗口,在我的例子中不包含任何内容。我在 tk.Tk.__init__(self) 之后添加了下一行: tk.Tk.withdraw(self) ,主窗口消失,同时仍然显示浮动窗口。 (2认同)

小智 10

这是我的解决方案:

from tkinter import *
from webbrowser import *


lastClickX = 0
lastClickY = 0


def SaveLastClickPos(event):
    global lastClickX, lastClickY
    lastClickX = event.x
    lastClickY = event.y


def Dragging(event):
    x, y = event.x - lastClickX + window.winfo_x(), event.y - lastClickY + window.winfo_y()
    window.geometry("+%s+%s" % (x , y))


window = Tk()
window.overrideredirect(True)
window.attributes('-topmost', True)
window.geometry("400x400+500+300")
window.bind('<Button-1>', SaveLastClickPos)
window.bind('<B1-Motion>', Dragging)
window.mainloop()
Run Code Online (Sandbox Code Playgroud)