Tkinter:鼠标拖动一个没有边框的窗口,例如.覆盖直接(1) [英] Tkinter: Mouse drag a window without borders, eg. overridedirect(1)
问题描述
关于如何创建允许用户用鼠标拖动无边框窗口的事件绑定的任何建议,例如.使用 overridedirect(1)
?
Any suggestions on how one might create event bindings that would allow a user to mouse drag a window without borders, eg. a window created with overridedirect(1)
?
用例:我们想创建一个浮动工具栏/调色板窗口(无边框),我们的用户可以在桌面上拖动它.
Use case: We would like to create a floating toolbar/palette window (without borders) that our users can drag around on their desktop.
这是我的想法(伪代码):
Here's where I'm at in my thinking (pseudo code):
window.bind( '
捕获鼠标的初始位置.', onMouseDown )
window.bind( '<Button-1>', onMouseDown )
to capture the initial position of the mouse.
window.bind( '
跟踪鼠标开始移动后的位置.
window.bind( '<Motion-1>', onMouseMove )
to track position of mouse once it starts to move.
计算鼠标移动了多少并计算newX
、newY
位置.
Calculate how much mouse has moved and calculate newX
, newY
positions.
使用 window.geometry( '+%d+%d' % ( newX, newY ) )
移动窗口.
Tkinter 是否公开了足够的功能来让我实现手头的任务?或者是否有更简单/更高级别的方法来实现我想做的事情?
Does Tkinter expose enough functionality to allow me to implement the task at hand? Or are there easier/higher-level ways to achieve what I want to do?
推荐答案
是的,Tkinter 公开了足够的功能来执行此操作,不,没有更简单/更高级别的方法来实现您想要做的事情.你的想法很正确.
Yes, Tkinter exposes enough functionality to do this, and no, there are no easier/higher-level ways to achive what you want to do. You pretty much have the right idea.
这是一个例子,虽然它不是唯一的方法:
Here's one example, though it's not the only way:
import tkinter as tk
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.start_move)
self.grip.bind("<ButtonRelease-1>", self.stop_move)
self.grip.bind("<B1-Motion>", self.do_move)
def start_move(self, event):
self.x = event.x
self.y = event.y
def stop_move(self, event):
self.x = None
self.y = None
def do_move(self, event):
deltax = event.x - self.x
deltay = event.y - self.y
x = self.winfo_x() + deltax
y = self.winfo_y() + deltay
self.geometry(f"+{x}+{y}")
app=App()
app.mainloop()
这篇关于Tkinter:鼠标拖动一个没有边框的窗口,例如.覆盖直接(1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!