screen_shot.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # -*- coding:utf-8 -*-
  2. import tkinter
  3. import tkinter.filedialog
  4. import os
  5. from PIL import ImageGrab
  6. from time import sleep
  7. from tkinter import StringVar, IntVar
  8. class ScreenCapture:
  9. def __init__(self):
  10. pass
  11. def start(self):
  12. self.root = tkinter.Tk()
  13. self.root.geometry('0x0+0+0')
  14. self.root.resizable(False, False)
  15. self.X = tkinter.IntVar(value=0)
  16. self.Y = tkinter.IntVar(value=0)
  17. self.selectPosition=None
  18. screenWidth = self.root.winfo_screenwidth()
  19. screenHeight = self.root.winfo_screenheight()
  20. self.top = tkinter.Toplevel(self.root, width=screenWidth, height=screenHeight)
  21. self.top.overrideredirect(True)
  22. self.canvas = tkinter.Canvas(self.top,bg='white', width=screenWidth, height=screenHeight)
  23. self.p_w_picpath = tkinter.PhotoImage(file=self.filename)
  24. self.canvas.create_image(screenWidth//2, screenHeight//2, image=self.p_w_picpath)
  25. def onLeftButtonDown(event):
  26. self.X.set(event.x)
  27. self.Y.set(event.y)
  28. #开始截图
  29. self.sel = True
  30. self.canvas.bind('<Button-1>', onLeftButtonDown)
  31. def onLeftButtonMove(event):
  32. if not self.sel:
  33. return
  34. global lastDraw
  35. try:
  36. self.canvas.delete(lastDraw)
  37. except Exception as e:
  38. pass
  39. lastDraw = self.canvas.create_rectangle(self.X.get(), self.Y.get(), event.x, event.y, outline='red',width=8)
  40. self.canvas.bind('<B1-Motion>', onLeftButtonMove)
  41. def onLeftButtonUp(event):
  42. self.sel = False
  43. try:
  44. self.canvas.delete(lastDraw)
  45. except Exception as e:
  46. pass
  47. #sleep(0.1)
  48. myleft, myright = sorted([self.X.get(), event.x])
  49. mytop, mybottom = sorted([self.Y.get(), event.y])
  50. self.selectPosition=(myleft,myright,mytop,mybottom)
  51. pic = ImageGrab.grab((myleft+1, mytop+1, myright, mybottom))
  52. self.destroy()
  53. if self.callback:
  54. self.callback(pic)
  55. self.canvas.bind('<ButtonRelease-1>', onLeftButtonUp)
  56. self.canvas.pack(fill=tkinter.BOTH, expand=tkinter.YES)
  57. def destroy(self):
  58. self.top.destroy()
  59. self.root.destroy()
  60. def are_capture(self,callback):
  61. self.callback = callback
  62. self.filename = 'temp.png'
  63. im = ImageGrab.grab()
  64. im.save(self.filename)
  65. im.close()
  66. self.start()
  67. self.root.state('icon')
  68. os.remove(self.filename)
  69. self.root.mainloop()
  70. # def are_capture(callback):
  71. # filename = 'temp.png'
  72. # im = ImageGrab.grab()
  73. # im.save(filename)
  74. # im.close()
  75. # capture = MyCapture(filename)
  76. # capture.callback = callback
  77. # capture.root.state('icon')
  78. # sleep(0.2)
  79. # os.remove(filename)
  80. # capture.root.mainloop()