from tkinter import *
import time
root = Tk()
canvas =Canvas(root, width=1000, height=1000, bg= '#2B2B2B')
canvas.pack()
#id1 white
x = 400
y = 400
r = 50
#rc2 orange
f = 100
d = 400
r2 =100
id1 = canvas.create_oval(x - r, y - r, x + r, y + r, outline='white')
id2 = canvas.create_oval(f - r2, d - r2, f + r2, d + r2, outline='#CC7832')
def move_circle():
for k in range(31):
time.sleep(0.025)
canvas.move(id2, 5, 0)
canvas.update()
def get_coords(id_num):
pos = canvas.coords(id_num)
x = (pos[0] + pos[2])/2
y = (pos[1] + pos[3])/2
print(x, y)
return x, y
from math import sqrt
def distance(id1, id2):
x1, y1 = get_coords(id1)
x2, y2 = get_coords(id2)
print("distance", x1, y1, x2, y2)
return sqrt((x2 - x1)**2 + (y2 - y1)**2)
def delete_circle(): #12
if distance(id1, id2) < (r+r2):
canvas.delete(id2)
move_circle()
delete_circle()
root.mainloop()
'''嗨大家好,我试图让圈子id2在点击id1时删除。目前这只有我的范围才有效 在移动圆函数中设置为31-89之间。我理解这种情况的原因是因为删除功能仅在移动循环功能完成循环时执行。我认为解决方案是以某种方式让delete函数访问循环期间发生的坐标更改。然而,我试图做到这一点,至少可以说是一块墙。任何帮助将非常感激。提前一百万感谢。
答案 0 :(得分:0)
你只需要find_overlapping方法。
基本示例:
id1 = canvas.create_oval(x - r, y - r, x + r, y + r, outline='white')
id2 = canvas.create_oval(f - r2, d - r2, f + r2, d + r2, outline='#CC7832')
id1_coords = canvas.coords(id1)
def move_circle(x, y):
canvas.move(id2, x, y)
if id2 not in canvas.find_overlapping(*id1_coords) :
canvas.after(100, move_circle, x, y)
else :
canvas.delete(id2)
move_circle(5, 0)
root.mainloop()