본문 바로가기
파이썬

파이썬 How to display picture and get mouse click coordinate on it

by º기록 2020. 10. 6.
반응형

Python (Windows)에서 그림을 표시 한 다음이 그림을 마우스로 클릭하고 그림 가장자리를 기준으로이 클릭의 좌표를 얻을 수 있는지 궁금합니다.

감사!

 

해결 방법

 

예, tkinter를 이해하면 가능하고 매우 쉽습니다. 여기에 빠른 스크립트가 있습니다.

from Tkinter import *
from tkFileDialog import askopenfilename
import Image, ImageTk

if __name__ == "__main__":
    root = Tk()

    #setting up a tkinter canvas with scrollbars
    frame = Frame(root, bd=2, relief=SUNKEN)
    frame.grid_rowconfigure(0, weight=1)
    frame.grid_columnconfigure(0, weight=1)
    xscroll = Scrollbar(frame, orient=HORIZONTAL)
    xscroll.grid(row=1, column=0, sticky=E+W)
    yscroll = Scrollbar(frame)
    yscroll.grid(row=0, column=1, sticky=N+S)
    canvas = Canvas(frame, bd=0, xscrollcommand=xscroll.set, yscrollcommand=yscroll.set)
    canvas.grid(row=0, column=0, sticky=N+S+E+W)
    xscroll.config(command=canvas.xview)
    yscroll.config(command=canvas.yview)
    frame.pack(fill=BOTH,expand=1)

    #adding the image
    File = askopenfilename(parent=root, initialdir="C:/",title='Choose an image.')
    img = ImageTk.PhotoImage(Image.open(File))
    canvas.create_image(0,0,image=img,anchor="nw")
    canvas.config(scrollregion=canvas.bbox(ALL))

    #function to be called when mouse is clicked
    def printcoords(event):
        #outputting x and y coords to console
        print (event.x,event.y)
    #mouseclick event
    canvas.bind("<Button 1>",printcoords)

    root.mainloop()

편집하지 않으면 기본 창 좌표계를 사용하여 콘솔에 인쇄됩니다. 캔버스 위젯은 왼쪽 상단 모서리를 0,0 포인트로 만들어서 printcoords 함수를 엉망으로 만들어야 할 수도 있습니다. 로드 된 그림 차원을 가져 오려면 canvas.bbox (ALL)을 사용하고 그대로 사용하는 대신 canvasx 및 canvasy 좌표를 사용하도록 전환 할 수 있습니다. tkinter를 처음 사용하는 경우; Google은 여기에서 끝낼 수 있도록 도와 드릴 것입니다. :).

 

참조 페이지 https://stackoverflow.com/questions/5501192

 

 

반응형

댓글