亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Tkinter圖像裁剪工具:使用多個矩形裁剪圖像,添加滾動條導致矩形位置錯誤

Tkinter圖像裁剪工具:使用多個矩形裁剪圖像,添加滾動條導致矩形位置錯誤

手掌心 2023-07-11 10:31:06
我只是 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.


查看完整回答
反對 回復 2023-07-11
  • 1 回答
  • 0 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號