如何显示图片并获得鼠标点击坐标 [英] How to display picture and get mouse click coordinate on it

查看:1624
本文介绍了如何显示图片并获得鼠标点击坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Python(Windows)中是否可以显示一些图片,然后在这张图片上点击鼠标,并获得相对于图片边缘的点击坐标。

I am wondering if it is possible in Python (Windows) to show some picture, then click with the mouse on this picture and get the coordinates of this click relative to picture edges.

谢谢!

推荐答案

是的,一旦你理解了tkinter,这是可能的,非常简单,这是一个快速的脚本:

Yes it is possible and pretty easy once you understand tkinter, here's a quick script:

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 coords而不是它的方式。如果你是tkinter的新手;谷歌应该能够帮助你从这里完成它:)。

Unedited it will print using the default window coordinate system to the console. The canvas widget makes the top left corner the 0,0 point so you may have to mess around with the printcoords function. To get the loaded picture dimension you would use canvas.bbox(ALL), and you might want to switch to using canvasx and canvasy coords instead of how it is. If you're new to tkinter; google should be able to help you finish it from here :).

这篇关于如何显示图片并获得鼠标点击坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆