以下是我找到tkinker透過canvas去拖拉圖案,
但是如何把背景換成我要的圖片?
canvas = tk.Canvas(master, width=700,height=500,bd=0, highlightthickness=0)
imgpath = 'path/to/yourfile'
img = Image.open(imgpath)
photo = ImageTk.PhotoImage(img)
canvas.create_image(1080, 720, image=photo)
以上是我找到tk的更換背景的碼,但不知道加在哪才對~
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
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()
你可以嘗試加在canvas顯示的地方看看,不知道這個是不是你要的效果
w = MyCanvas(master)
imgpath = 'imagePath' #add image
img = Image.open(imgpath)
photo = ImageTk.PhotoImage(img)
w.pack(fill=tk.BOTH,expand=1)
# Display image
w.create_image(0, 0, image=photo, anchor="nw")
print(w.find_all())
b=Block(w)