我只是 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
提交
取消