将图形封装到了block的类里面,为的就是可以同时拖动两个图形。
import tkinter as tk
print(tk.CURRENT)
class Block():
def __init__(self, canvas:tk.Canvas):
self.item_ids = []
self.canvas = canvas
oval1 = self.canvas. create_oval(80.4,80,50,50,fill='white')
oval2 = self.canvas. create_oval(180,180,50,50, fill='white')
self.item_ids.append(oval1)
self.item_ids.append(oval2)
self.set_item_mapping()
def move_to(self, x:float , y:float):
for id in self.item_ids:
self.canvas.move_to(id, x,y)
def set_item_mapping(self):
for id in self.item_ids:
self.canvas.itemMap[id]=self
class MyCanvas(tk.Canvas):
def __init__(self,parent):
super().__init__(parent)
self.itemToMove = None
self.relativePos = ()
self.itemMap = {}# 东西的映射。当拖动等事件发生时,修改这个字典中的对象。
self.bind('<ButtonPress-1>',self.on_mouse_down)
self.bind('<B1-Motion>',self.on_mouse_drag)
def on_mouse_down(self,event):
self.relativePos=()
a = self.find_withtag(tk.CURRENT)
if len(a)>=1:
coor = self.coords(a[0])
x,y = event.x-coor[0],event.y-coor[1]
self.relativePos = (x,y)
self.itemToMove = a[0]
else:
self.itemToMove = None
def move_to(self,item_id,x,y):
pos = self.coords(item_id)
self.move(item_id, x-pos[0], y-pos[1])
def on_mouse_drag(self,event):
if not self.itemToMove: # 如果没有要移动的对象,就直接return,防止出现奇奇怪怪的错误。
return
a = self.find_withtag(tk.CURRENT)
if len(a)>=1:
self.itemMap[a[0]].move_to(event.x-self.relativePos[0], event.y-self.relativePos[1])
canvas_width = 190
canvas_height =150
master = tk.Tk()
w = MyCanvas(master)
w.pack(fill=tk.BOTH,expand=1)
print(w.find_all())
b=Block(w)
tk.mainloop()