我目前正在使用 Tkinter,并且正在嘗試制作可拖動的畫布影像,這是我從另一個堆疊溢位問題“制作”/編輯的代碼,第二個是特別的。當我使用時,代碼對我有用tk.Frame(),但它給出了一個錯誤Canvas.create_image()。所以我對其進行了一些編輯,但現在當我拖動它時它似乎完全在移動影像
我的代碼:
from tkinter import *
import pyautogui
x,y=pyautogui.size()
tk = Tk()
c = Canvas(tk, width=x, height=y)
c.place(x=-2,y=-3)
img = ImageTk.PhotoImage(PIL.Image.open(r"Data\backgrounds\background.jpg"))
c.create_image(0, 0, image=img, anchor=NW)
def command6():
print("command6")
def make_draggable(widget,btn="<Button-1>",motion="<B1-Motion>"):
def __draggable__(widget):
c.tag_bind(btn,btn,on_drag_start)
c.tag_bind(motion,motion,on_drag_motion)
def on_drag_start(event):
widget = event.widget
widget._drag_start_x = event.x
widget._drag_start_y = event.y
def on_drag_motion(event):
widget = event.widget
x = widget.winfo_x() - widget._drag_start_x event.x
y = widget.winfo_y() - widget._drag_start_y event.y
widget.move(widget,x, y)
__draggable__(widget)
APP_6 = r'apps\File.png'
APP_6 = PIL.Image.open(APP_6)
APP_6 = APP_6.resize((48,48),PIL.Image.ANTIALIAS)
APP_6 = ImageTk.PhotoImage(APP_6)
image_6 = ImageTk.PhotoImage(PIL.Image.open(r"apps\File.png"))
image_id_6 = c.create_image(48,48, image=APP_6)
c.move(image_id_6, 1,y-735)
c.tag_bind(image_id_6, '<Button-1>',command6)
make_draggable(image_id_6)
tk.mainloop()
這不會在控制臺中產生任何錯誤或任何不需要的輸出。
uj5u.com熱心網友回復:
函式內部有幾個問題make_draggable():
- 第一個引數
.tag_bind()是畫布專案的專案 ID。對于您的情況,它widget是make_draggable(). 所以以下幾行:
c.tag_bind(btn,btn,on_drag_start)
c.tag_bind(motion,motion,on_drag_motion)
應該改為
c.tag_bind(widget, btn, on_drag_start)
c.tag_bind(widget, motion, on_drag_motion)
同樣適用于c.move(...)內部on_drag_motion()
- 移影片布專案的邏輯/計算錯誤
下面是修改后的make_draggable()函式:
def make_draggable(widget, btn="<Button-1>", motion="<B1-Motion>"):
def __draggable__(widget):
c.tag_bind(widget, btn, on_drag_start)
c.tag_bind(widget, motion, on_drag_motion)
c._item_id = widget # save the item ID for later use
def on_drag_start(event):
widget = event.widget
# get the top-left coordinates of the selected item
x, y, *_ = widget.bbox(widget._item_id)
# save the offset of current mouse position from the top-left coordinates
widget._dx = event.x - x
widget._dy = event.y - y
def on_drag_motion(event):
widget = event.widget
# calculate the top-left coordinates of the item that the item to be moved to
x = event.x - widget._dx
y = event.y - widget._dy
# move the item using moveto() instead of move()
widget.moveto(widget._item_id, x, y)
__draggable__(widget)
由于上述邏輯僅適用于最后一次呼叫的專案make_draggable()。最好使用類而不是函式:
class make_draggable():
def __init__(self, item_id, btn="<Button-1>", motion="<B1-Motion>"):
self.item_id = item_id
c.tag_bind(item_id, btn, self.on_drag_start, add=True)
c.tag_bind(item_id, motion, self.on_drag_motion, add=True)
def on_drag_start(self, event):
x, y, *_ = event.widget.bbox(self.item_id)
self.dx, self.dy = event.x-x, event.y-y
def on_drag_motion(self, event):
event.widget.moveto(self.item_id, event.x-self.dx, event.y-self.dy)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/448492.html
