[英]How to fix a widget in a grid row and column while the user is dragging it?
I want a widget which is been dragged by the user to be fixed in a specific grid cell when the widget comes near it, is there any way to do it in tkinter?我想要一个被用户拖动的小部件在小部件靠近它时固定在特定的网格单元中,有没有办法在 tkinter 中做到这一点? I managed to make the widget draggable by taking the mouse position of user as he drags the widget, but i dont know how to make it fix into a grid cell.
我设法通过在用户拖动小部件时使用鼠标 position 使小部件可拖动,但我不知道如何将其固定到网格单元中。
this is what i use currently to move widgets这是我目前用来移动小部件的
def make_draggable(self):
def drag_start(event):
widget = self
widget = event.widget
self._drag_start_x = event.x
self._drag_start_y = event.y
def drag_motion(event):
widget = self
widget = event.widget
x = self.winfo_x() - self._drag_start_x + event.x
y = self.winfo_y() - self._drag_start_y + event.y
self.place(x=x, y=y)
self.bind("<Button-1>", drag_start)
self.bind("<B1-Motion>", drag_motion)
for example, if the grid cell left top corner position is (x=10,y=10) I need the button to get fixed in the cell when its position is near that value (like 9,9 8,8 9,5 etc)例如,如果网格单元格左上角 position 是 (x=10,y=10) 当 position 接近该值(如 9,9 8,8 9,5 等)时,我需要将按钮固定在单元格中)
Based on what I have understood from your question, I have tried the following根据我从您的问题中了解到的情况,我尝试了以下方法
from tkinter import *
class Drag:
def __init__(self,widget):
self.widget=widget
self.widget.bind("<Button-1>", self.drag_start)
self.widget.bind("<B1-Motion>", self.drag_motion)
self.grid=(100,100)
self.margin=(20,20)
def drag_start(self,event):
self._drag_start_x = event.x
self._drag_start_y = event.y
def drag_motion(self,event):
x = self.widget.winfo_x() - self._drag_start_x + event.x
y = self.widget.winfo_y() - self._drag_start_y + event.y
if (
x%self.grid[0] in range(self.margin[0]) and
y%self.grid[1] in range(self.margin[1])
):
self.widget.place(x=x-x%self.grid[0],y=y-y%self.grid[1])
else:
self.widget.place(x=x, y=y)
root=Tk()
root.minsize(300,200)
label=Label(root,text='Drag Me',bg='yellow')
label.pack()
Drag(label)
root.mainloop()
This basically creates grid of "cells" of height and width 100
and it clips it to the cell if it is in 20
pixel range of the top left corner of the cell.这基本上创建了高度和宽度为
100
的“单元格”网格,如果它位于单元格左上角的20
像素范围内,则将其剪辑到单元格中。 This is basically done by taking the remainders of the current coordinates when divided by the cell's height/width using the modulo %
operator and comparing if this lies in the desired range.这基本上是通过使用模
%
运算符将当前坐标除以单元格的高度/宽度并比较其是否在所需范围内来完成的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.