鼠标截图区域

Screenshot area from mouse

我正在尝试截取鼠标指定的屏幕截图区域(x、y 坐标)。

下一段代码打开一个不透明的window,然后它开始监听鼠标左键,当它选择一个区域时它绘制一个红色边框颜色,然后在该特定区域截取屏幕截图。我遇到的问题是删除我之前设置的不透明颜色。

注意:我使用不透明的颜色让用户知道程序何时准备好截取屏幕截图区域。

from pynput.mouse import Listener
from PIL import Image, ImageGrab
import tkinter as tk

root = tk.Tk()


########################## Set Variables ##########################
ix = None
iy = None

#Get the current screen width and height
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()


#Get and print coordinates
def on_move(x, y):
    print('Pointer moved to {0}'.format( (x, y) ))

#Start and End mouse position
def on_click(x, y, button, pressed):
    global ix, iy
    if button == button.left:              
        #Left button pressed then continue
        if pressed:
            ix = x
            iy = y
            print('left button pressed at {0}'.format( (x, y) ))
        else:    
            print('left button released at {0}'.format( (x, y) ))
            canvas.create_rectangle(ix, iy, x, y, outline="red", width = 5)#Draw a rectangle
            canvas.pack()
            img = ImageGrab.grab(bbox = (ix, iy, x, y))#Take the screenshot
            img.save('screenshot.png')#Save screenshot
            root.quit()#Remove tkinter window

    if not pressed:
        # Stop listener
        return False


#Print the screen width and height
print(screen_width, screen_height)


root_geometry = str(screen_width) + 'x' + str(screen_height) #Creates a geometric string argument
root.geometry(root_geometry) #Sets the geometry string value

root.overrideredirect(True)
root.wait_visibility(root)
root.wm_attributes("-alpha", 0.3)#Set windows transparent

canvas = tk.Canvas(root, width=screen_width, height=screen_height)#Crate canvas
canvas.config(cursor="cross")#Change mouse pointer to cross
canvas.pack()

# Collect events until released
with Listener(on_move=on_move, on_click=on_click) as listener:
    root.mainloop()#Start tkinter window
    listener.join()

系统信息:

我认为您需要在截图之前再次更新 root.wm_attributes。所以像这样:

# Start and End mouse position
def on_click(x, y, button, pressed):
    global ix, iy

    if button == button.left:

        # Left button pressed then continue
        if pressed:
            ix = x
            iy = y
            print('left button pressed at {0}'.format((x, y)))
        else:
            print('left button released at {0}'.format((x, y)))
            root.wm_attributes('-alpha', 0)
            img = ImageGrab.grab(bbox=(ix, iy, x, y))  # Take the screenshot
            root.quit()  # Remove tkinter window
            img.save('screenshot_area.png')  # Save the screenshot

    if not pressed:
        # Stop listener
        return False

也许你可以使用 tkinter.canvas 作为矩形。