每个方法都create_XXX给出id创建的对象
id = canvas.create_rectangle(...)
您可以将其保留在列表中,以便在需要时访问所有对象。
要更改对象的选项,您可以使用它id
canvas.itemconfig(id, fill='blue')
您可以绑定到单击左键( )Canvas时将执行的函数<Button-1>
canvas.bind('<Button-1>', on_click)
这个函数会得到event鼠标位置event.x,event.y你可以用它在画布上找到对象
selected_id = canvas.find_overlapping(event.x, event.y, event.x+1, event.y+1)
现在您可以取消选择所有项目并仅选择单击的项目
for id_ in all_ids:
canvas.itemconfig(id_, fill='red')
if selected_id:
canvas.itemconfig(selected_id, fill='blue')
import tkinter as tk
# --- functions ---
def on_click(event):
#print(event)
selected_id = canvas.find_overlapping(event.x, event.y, event.x+1, event.y+1)
print(selected_id)
for id_ in all_ids:
canvas.itemconfig(id_, fill='red')
if selected_id:
canvas.itemconfig(selected_id, fill='blue')
# --- main ---
root = tk.Tk()
canvas = tk.Canvas()
canvas.pack()
canvas.bind('<Button-1>', on_click)
all_ids = []
for x in range(10, 301, 60):
id_ = canvas.create_rectangle((x, 10, x+50, 60), fill='red')
all_ids.append(id_)
root.mainloop()
文件:帆布