我只是 Python 和 Tkinter 的初学者,我正在尝试编写一个应用程序来裁剪图像中的多个区域并将它们保存为单独的图像,我可以通过绘制多个矩形来裁剪图像,但是在添加滚动条后使用鼠标指针绘制矩形时,鼠标位置出现错误,由于滚动效果,鼠标指针位置稍远。我还尝试添加放大和缩小功能,您能否建议我如何实现这一目标。import osimport tkinter as tkimport tkinter.filedialog as filedialogfrom PIL import Image, ImageTk, ImageGrabWIDTH, HEIGHT = 1200, 800topx, topy, botx, boty = 0, 0, 0, 0rect_id = Nonepath = "test.jpg"rect_list = list()rect_main_data = list()ImageFilePath = ""ImgOpen = NoneprodDir = ""ImageFound = Falsewindow = tk.Tk()window.title("Image Croping Tool")window.geometry('%sx%s' % (WIDTH, HEIGHT))window.configure(background='grey')ImageFrame = tk.Frame(window, width=WIDTH,height=HEIGHT - 70, borderwidth=1)ImageFrame.pack(expand=True, fill=tk.BOTH)ImageFrame.place(x=0,y=71)rawImage = Image.open("test.jpg")img = ImageTk.PhotoImage(rawImage)canvasWidth, canvasHeight = rawImage.sizecanvas = tk.Canvas(ImageFrame, width=canvasWidth, height=canvasHeight - 70, borderwidth=2, highlightthickness=2,scrollregion=(0,0,canvasWidth,canvasHeight))def get_mouse_posn(event): global topy, topx topx, topy = event.x, event.ydef update_sel_rect(event): global rect_id global topy, topx, botx, boty botx, boty = event.x, event.y canvas.coords(rect_id, topx, topy, botx, boty) # Update selection rect.def draw_rect(self): draw_data = canvas.create_rectangle(topx,topy,botx,boty,outline="green", fill="") rect_list.append((topx,topy,botx,boty)) rect_main_data.append(draw_data) def GetImageFilePath(): global ImageFilePath global ImageFound global img global canvas global ImageFrame test = False if (ImageFound): canvas.destroy() canvas = tk.Canvas(ImageFrame, width=canvasWidth, height=canvasHeight - 70, borderwidth=2, highlightthickness=2,scrollregion=(0,0,canvasWidth,canvasHeight))
1 回答

沧海一幻觉
TA贡献1824条经验 获得超5个赞
因为event.x和event.y始终相对于画布的左上角。如果画布没有滚动,它们将与真实坐标匹配。但当画布滚动时则不然。
但是,您可以使用canvas.canvasx()和canvas.canvasy()函数将鼠标位置转换为画布中的真实坐标:
def get_mouse_posn(event):
global topy, topx
topx, topy = canvas.canvasx(event.x), canvas.canvasy(event.y) # convert to real canvas coordinates
def update_sel_rect(event):
global botx, boty
botx, boty = canvas.canvasx(event.x), canvas.canvasy(event.y) # convert to real canvas coordinates
canvas.coords(rect_id, topx, topy, botx, boty) # Update selection rect.
添加回答
举报
0/150
提交
取消