Tkinter图像裁剪工具:使用多个矩形裁剪图像,添加滚动条导致矩形位置错误

我只是 Python 和 Tkinter 的初学者,我正在尝试编写一个应用程序来裁剪图像中的多个区域并将它们保存为单独的图像,我可以通过绘制多个矩形来裁剪图像,但是在添加滚动条后使用鼠标指针绘制矩形时,鼠标位置出现错误,由于滚动效果,鼠标指针位置稍远。


我还尝试添加放大和缩小功能,您能否建议我如何实现这一目标。


import os

import tkinter as tk

import tkinter.filedialog as filedialog

from PIL import Image, ImageTk, ImageGrab



WIDTH, HEIGHT = 1200, 800

topx, topy, botx, boty = 0, 0, 0, 0

rect_id = None

path = "test.jpg"

rect_list = list()

rect_main_data = list()

ImageFilePath = ""

ImgOpen = None

prodDir = ""

ImageFound = False


window = 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.size

canvas = 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.y


def 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))

    

手掌心
浏览 177回答 1
1回答

沧海一幻觉

因为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 coordinatesdef 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.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python