亲宝软件园·资讯

展开

Python截图工具

晋升阁 人气:0

这是工作期间同事想要个截完图之后可以显示并且永远前置的截图小工具(即不会被其他程序覆盖)直接上代码:

# # -*- coding: utf-8 -*-
import tkinter as tk
import pyautogui
import tkinter
from PIL import ImageTk
from PIL import Image
 
root = tk.Tk()
root.wm_attributes('-topmost', 1)
 
root.overrideredirect(True)  # 隐藏窗口的标题栏
# root.attributes("-alpha", 0.3)    # 窗口透明度70 %
root.attributes("-alpha", 0.4)  # 窗口透明度60 %
# root.geometry("300x200+10+10")      # 设置窗口大小与位置
root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
root.configure(bg="blue")
 
# 当工具条
canvas = tk.Canvas(root)
canvas.configure(width=300)
canvas.configure(height=100)
canvas.configure(bg="yellow")
canvas.configure(highlightthickness=0)  # 高亮厚度
canvas.place(x=(root.winfo_screenwidth() - 500), y=(root.winfo_screenheight() - 300))
canvas.create_text(150, 50, font='Arial -20 bold', text='ESC退出,假装工具条')
 
# 再创建1个Canvas用于圈选
cv = tk.Canvas(root)
x, y = 0, 0
xstart, ystart = 0, 0
 
 
def move(event):
    global x, y, xstart, ystart
    new_x = (event.x - x) + canvas.winfo_x()
    new_y = (event.y - y) + canvas.winfo_y()
    s = "300x200+" + str(new_x) + "+" + str(new_y)
    canvas.place(x=new_x - xstart, y=new_y - ystart)
    print("s = ", s)
    print(root.winfo_x(), root.winfo_y())
    print(event.x, event.y)
 
 
# 鼠标左键按下
def button_1(event):
    global x, y, xstart, ystart
    x, y = event.x, event.y
    xstart, ystart = event.x, event.y
    print("event.x, event.y = ", event.x, event.y)
    xstart, ystart = event.x, event.y
    cv.configure(height=1)
    cv.configure(width=1)
    cv.place(x=event.x, y=event.y)
 
 
# 鼠标左键按下并移动
def b1_Motion(event):
    global x, y
    x, y = event.x, event.y
    print("event.x, event.y = ", event.x, event.y)
    cv.configure(height=event.y - ystart)
    cv.configure(width=event.x - xstart)
 
 
# 鼠标左键松开
def buttonRelease_1(event):
    global x, y, xstart, ystart
    x, y = event.x, event.y
    print("event.x, event.y = ", event.x, event.y)
    Pstart = [0, 0]
    cv.place_forget()
    img = pyautogui.screenshot(region=[xstart, ystart, x - xstart, y - ystart])  # x,y,w,h
    img.save('screenshot.png')
 
 
# 退出
def sys_out(even):
    root.destroy()
    func()
 
# 绑定事件
canvas.bind("<B1-Motion>", move)
# 绑定事件到Esc键,当按下Esc键就会调用sys_out函数,弹出对话框
root.bind('<Escape>', sys_out)
root.bind("<Button-1>", button_1)
root.bind("<B1-Motion>", b1_Motion)
root.bind("<ButtonRelease-1>", buttonRelease_1)
img_png = None
def func():
    root1 = tk.Tk()
    root1.wm_attributes('-topmost', 1)
    img_open = Image.open("screenshot.png")
    global img_png
    img_png = ImageTk.PhotoImage(img_open)
    label_img = tk.Label(root1, image = img_png)
    label_img.pack()
 
root.mainloop()

具体用法是运行程序、选中区域(支持多次选定,以最后一次选定为主)、按esc完成截图同时弹出永远前置的截图照片窗体。

我打包了发给同事同事说很好用,就是差个快捷键。

其实也很简单,只须打包成exe程序后右击属性中设置快捷键即可~

加载全部内容

相关教程
猜你喜欢
用户评论