如何在 tkinter canvas 上找到重叠的对象?
How can I find overlapping objects on a tkinter canvas?
有什么简单的方法可以找到重叠的对象 ID?
这是代码示例:
import tkinter as tk
import random as rand
class GUI:
def __init__(self, master, width, height):
self.master = master
self.w = width
self.h = height
self.canvas = tk.Canvas(master, width=width, height=height)
self.canvas.pack()
self.create_objects()
def create_objects(self):
r = 5
for i in range(100):
x = rand.uniform(0,1)*width
y = rand.uniform(0,1)*height
self.canvas.create_oval(x-r,y-r,x+r,y+r, fill="red")
def find_overlaps(self):
pass
width = 800
height = 600
root = tk.Tk()
app = GUI(root, width, height)
root.mainloop()
我希望 find_overlaps 函数给我重叠的对象 ID 对(如果发生这种情况,则为三元组)。有什么easy/efficient方法可以做到吗?
您可以在此处执行以下步骤:
- 获取您在
canvas
上创建的对象的 ID 元组。您可以使用 canvas.find_all()
方法来完成。
- 使用
canvas.coords(id)
获取这些对象的坐标。
我已经检查了 canvas
的标准 find_overlapping
方法。它有助于确定哪些对象仅与特定矩形重叠,我想您需要借助此方法使用一些数学来解决您提到的问题。虽然,我找到了一个不错的选择,而不是基于 find_overlapping
:
def find_overlaps(self):
r = 5
X = []
tags = self.canvas.find_all() #finds tags of all the object created
for tag in tags:
x0, y0, x1, y1 = self.canvas.coords(tag) # corresponding coordinates
center = [(x0+x1)/2, (y0+y1)/2] #centers of objects
X.append(center)
tree = cKDTree(X)
print(tree.query_pairs(2*r))
输出
这是一组标签:
{(2, 63), (10, 93), (70, 82), (8, 45)}
备注
from scipy.spatial import cKDTree
是必需的
有什么简单的方法可以找到重叠的对象 ID? 这是代码示例:
import tkinter as tk
import random as rand
class GUI:
def __init__(self, master, width, height):
self.master = master
self.w = width
self.h = height
self.canvas = tk.Canvas(master, width=width, height=height)
self.canvas.pack()
self.create_objects()
def create_objects(self):
r = 5
for i in range(100):
x = rand.uniform(0,1)*width
y = rand.uniform(0,1)*height
self.canvas.create_oval(x-r,y-r,x+r,y+r, fill="red")
def find_overlaps(self):
pass
width = 800
height = 600
root = tk.Tk()
app = GUI(root, width, height)
root.mainloop()
我希望 find_overlaps 函数给我重叠的对象 ID 对(如果发生这种情况,则为三元组)。有什么easy/efficient方法可以做到吗?
您可以在此处执行以下步骤:
- 获取您在
canvas
上创建的对象的 ID 元组。您可以使用canvas.find_all()
方法来完成。 - 使用
canvas.coords(id)
获取这些对象的坐标。
我已经检查了 canvas
的标准 find_overlapping
方法。它有助于确定哪些对象仅与特定矩形重叠,我想您需要借助此方法使用一些数学来解决您提到的问题。虽然,我找到了一个不错的选择,而不是基于 find_overlapping
:
def find_overlaps(self):
r = 5
X = []
tags = self.canvas.find_all() #finds tags of all the object created
for tag in tags:
x0, y0, x1, y1 = self.canvas.coords(tag) # corresponding coordinates
center = [(x0+x1)/2, (y0+y1)/2] #centers of objects
X.append(center)
tree = cKDTree(X)
print(tree.query_pairs(2*r))
输出
这是一组标签:
{(2, 63), (10, 93), (70, 82), (8, 45)}
备注
from scipy.spatial import cKDTree
是必需的