有截图的需要,现成截图工具用着不是那么舒服,python命令行程序截图很香,但是网上没有见到有人介绍GUI,不能用鼠标画框截图...很烦躁...
想着也学过几天Tkinter,能不能用Tkinter做个截图工具,用到了pyautogui, im = pyautogui.screenshot()截图,Pillow/PIL做裁剪,Tkinter做截图界面&鼠标事件处理... 终于磕磕巴巴做了个可以用的截图工具. 后缀名改为".pyw"可以隐藏黑框框.
现在可以愉快快速的截图了.....
#张秀才
#2023/06/21__14:48
#截图 alt+F4 可以退出
#非专业人士 .给需要用的人
import tkinter as tk
import pyautogui
import win32gui
import os,sys,time
from PIL import Image
def getscreen():
r""" 截屏全屏"""
global im
im = pyautogui.screenshot()
try:
pass
#im.save(f"{os.getcwd()}/screenshot_temp.png")
except:
pass
return im
def savescrimg(s1=30,s2=135,s3=940,s4=800):
r''' 保存指定区域屏图 '''
global im
SaveFileName=time.strftime('%Y-%m-%d_%H_%M_%S');
im = pyautogui.screenshot(region=(s1,s2,s3,s4))
try:
im.save(f"{os.getcwd()}/screenshot.png")
except:
pass
pass
return im
getscreen()#time.sleep(1)
root = tk.Tk()
root.title('截图工具') # 设置窗口标题。
try:
root.iconbitmap('3D.ico') # 设置窗口左上角的图标。
except:
pass
WIDTH =window_x = root.winfo_screenwidth();
HEIGHT =window_y = root.winfo_screenheight()#"获取电脑屏幕尺寸大小"
x =0;y =0;
root.geometry(f'{WIDTH}x{HEIGHT}+{int(x)}+{int(y)}')
root.resizable(width=True, height=True) # 设置是否禁止调整窗口的宽和高。
win_width = root.winfo_width() #获取窗口宽度(单位:像素)
win_height = root.winfo_height() #获取窗口高度(单位:像素)
x=root.winfo_x() #获取窗口左上角的 x 坐标(单位:像素)
y=root.winfo_y() #获取窗口左上角的 y 坐标(单位:像素)
root.overrideredirect(True) #参数True,隐藏窗口标题栏。即不显示窗口标题和最大化、最小化、关闭按钮。
root.attributes("-alpha",0.5) #设置窗口的透明度 0.8, 参数为 0 到 1。
w = tk.Canvas(root, width =WIDTH, height = HEIGHT)
w.pack()
_1x=0;_1y=0;_2x=0;_2y=0;
def handleMotion(event):
global _x
global _y
global _x
global _y
lb1['text'] = '你移动了光标的所在位置'
lb2['text'] = '目前光标位置:x ='+ str(event.x)+';y='+str(event.y)
w.delete("all")
w.delete()
w.create_rectangle(_1x, _1y, event.x,event.y, fill = "blue")
#print('光标当前位置',event.x,event.y)
def handle_ML(event):
global _1x
global _1y
global _2x
global _2y
_1x=event.x
_1y=event.y
print("ML");print(f"{event.x},{event.y}");
pass
def handle_MR(event):
global _1x
global _1y
global _2x
global _2y
_2x=event.x;_2y=event.y
print("MR");print(f"{event.x},{event.y}");
def handle_RL(event):
print("RL");print(f"{event.x},{event.y}");
def handle_RR(event):
print("RR");print(f"{event.x},{event.y}");
box =(_1x,_1y,_2x,_2y)
imb = im.crop(box)
imb.save(f"{os.getcwd()}/{time.strftime('%Y-%m-%d_%H_%M_%S')}.png")
exit()
lb1 = tk.Label(w,text='没有任何事件触发', bg='purple', ) ;lb1.place (x=20,y=900)
lb2 = tk.Label(w,text='...'); lb2.place (x=16,y=930)
w.bind('<Motion>',handleMotion)#
w.bind('<ButtonPress-1>',handle_ML)#鼠标左键按下事件
w.bind('<ButtonPress-3>',handle_MR)#鼠标右键按下事件
w.bind('<ButtonRelease-1>',handle_RL)#鼠标左键抬起事件
w.bind('<ButtonRelease-3>',handle_RR)#鼠标右键抬起事件
tk.mainloop()
好了,愉快的玩耍吧,快速截图...90行搞了一个小时. 结束..