利用Python實現一個簡易的截圖工具

這是工作期間同事想要個截完圖之後可以顯示並且永遠前置的截圖小工具(即不會被其他程序覆蓋)直接上代碼:

# # -*- 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程序後右擊屬性中設置快捷鍵即可~

到此這篇關於利用Python實現一個簡易的截圖工具的文章就介紹到這瞭,更多相關Python截圖工具內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: