1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
| #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
#
"""whiteboard.py
Shootscreen utility for Python 2.x.
Needed : Tkinter et PIL
Under Linux : ImageMagick
Under Mac : screencapture
"""
import sys
import os
try:
import Tkinter as Tk
import tkFileDialog as tkFD
from Tkconstants import *
import Image, ImageTk
except:
import tkinter as Tk
import tkinter.filedialog as tkFD
from tkinter.constants import *
# WARNING: Experimental import for PIL under Python 3.
from PIL import Image, ImageTk
class ScreenCap(object):
def __init__(self):
"""Screenshot class"""
if sys.platform == 'linux2':
self.grab = self._GarbLinux
elif sys.platform == 'win32':
import Image, ImageGrab
self.grab = self._GrabWin
elif sys.platform == 'darwin':
self.grab = self._GrabMac
else:
sys.exit(1)
self._currentf = None
def _FicNormalyze(self, name):
"""Internal Function for generate temp file.
Use home user directory for rights.
"""
if name:
if os.path.basename(name) == name:
_grabfile = os.path.join(os.path.expanduser('~'), name)
else:
_grabfile = name
else:
# default name
_grabfile = os.path.join(os.path.expanduser('~'), 'scrcap.jpg')
self._currentf = _grabfile
return _grabfile
def _GarbLinux(self, name=None):
"""Internal function for screen capture under Linux
Use ImageMagick import utility
"""
_grabfile = self._FicNormalyze(name)
_grabcommand = "import -silent -window root " + _grabfile
os.system(_grabcommand)
return _grabfile
def _GrabWin(self, name=None):
"""Internal function for screen capture under Windows.
Use PIL ImageGrab.
"""
try:
import ImageGrab
except:
# Experimental import for PIL under Python 3.
from PIL import ImageGrab
_grabfile = self._FicNormalyze(name)
ImageGrab.grab().save(_grabfile, "JPEG")
return _grabfile
def _GrabMac(self, name=None):
"""Internal function for screen capture under Windows.
Use screencapture command.
"""
_grabfile = self._FicNormalyze(name)
_grabcommand = "screencapture -m -x -t jpg " + _grabfile
os.system(_grabcommand)
return _grabfile
def delete(self):
"""Internal function. Delete temp file."""
if os.path.isfile(self._currentf):
os.remove(self._currentf)
class MainMenu(object):
"""Main menu class"""
def __init__(self, master, bg=None, fg=None, activefg=None):
self.master = master
# {'titre': callback}
self._DicItem = {}
self._DicCtrl = {}
if bg:
self._Bg = bg
else:
self._Bg = 'gray'
if fg:
self._Fg = fg
else:
self._Fg = 'black'
if activefg:
self._ActiveFg = activefg
else:
self._ActiveFg = 'blue'
def _RootQuit(self, event):
"""Internal function"""
self.master.quit()
def _Position(self, widget, x, y):
"""Internal function for the geometry"""
# Update the widget
widget.update()
# Get the geometry
reqw = widget.winfo_reqwidth()
reqh = widget.winfo_reqheight()
winw = widget.winfo_screenwidth()
winh = widget.winfo_screenheight()
posx = x - (reqw/2)
if x + reqw/2 > winw:
posx = posx - ((x + reqw/2) - winw)
elif x - reqw/2 < 0:
posx = 0
posy = y - reqh/2
if y + reqh/2 > winh:
posy = posy - ((y + reqh/2) - winh)
elif y - reqh/2 < 0:
posy = 0
# Set the widget geometry
widget.geometry("%dx%d+%d+%d" % (reqw, reqh, posx, posy))
def ShowMenu(self, event=None):
# Clean the screen
for widget in (widget for widget in self.master.winfo_children()
if isinstance(widget, Tk.Toplevel)):
return
# Get the position
position = self.master.winfo_pointerxy()
x, y = position[0], position[1]
# Create the Toplevel
self._TopMenu = Tk.Toplevel(self.master, bg=self._Bg)
self._TopMenu.withdraw()
CtnFrm = Tk.Frame(self._TopMenu, bd=1, relief=RIDGE, bg=self._Bg)
Tk.Label(CtnFrm, text='MENU', fg=self._Fg,
bg=self._Bg).pack(padx=3, pady=2)
Tk.Frame(CtnFrm, height=2, bd=1, relief=SUNKEN,
bg=self._Bg).pack(fill=X, padx=5, pady=5)
# Labels
_Lab = {}
_tri = []
# Sort _DicItem keys
for cle in self._DicItem.keys():
_tri.append(cle)
_tri.sort()
for elems in _tri:
_Lab[elems] = Tk.Label(CtnFrm, text=elems, fg=self._Fg, bg=self._Bg)
_Lab[elems].pack(padx=3, pady=2)
# bind the callback
_Lab[elems].bind("<1>", self._DicItem[elems])
# focus
self._FocusCtrl(_Lab[elems])
_tri = []
for cle in self._DicCtrl.keys():
_tri.append(cle)
_tri.sort()
for elems in _tri:
_Lab[elems] = Tk.Label(CtnFrm, text=elems, fg=self._Fg, bg=self._Bg)
_Lab[elems].pack(padx=3, pady=2)
_Lab[elems].bind("<1>", self._DicCtrl[elems])
self._FocusCtrl(_Lab[elems])
LabelQuit = Tk.Label(CtnFrm, text='Quitter', fg=self._Fg, bg=self._Bg)
LabelQuit.pack(padx=3, pady=2)
self._FocusCtrl(LabelQuit)
CtnFrm.pack(padx=3, pady=2)
LabelQuit.bind("<1>", self._RootQuit)
self._Position(self._TopMenu, x, y)
self._TopMenu.bind("<1>", self._Hide)
self._TopMenu.overrideredirect(True)
self._TopMenu.deiconify()
def _Hide(self, event=None):
self._TopMenu.destroy()
def _FocusCtrl(self, widget):
widget.bind("<Leave>", lambda e: self._NotActive(widget))
widget.bind("<Enter>", lambda e: self._IsActive(widget))
def _IsActive(self, widget):
# Text color
widget['fg'] = self._ActiveFg
widget.update()
def _NotActive(self, widget):
widget['fg'] = self._Fg
widget.update()
# for items and controls
def additem(self, name, cb):
self._DicItem[name] = cb
def delitem(self, name):
del self._DicItem[name]
def addctrl(self, name, cb):
self._DicCtrl[name] = cb
def delctrl(self, name):
del self._DicCtrl[name]
class GUI(Tk.Tk):
def __init__(self, parent):
Tk.Tk.__init__(self, parent)
self.title('Whiteboard')
self._Pts = []
self._ToTrace = None
self.Color = Tk.StringVar()
self.Color.set('red')
self.Width = Tk.IntVar()
self.Width.set(3)
self.Sccap = ScreenCap()
_Img = self.Sccap.grab(name='scrcap.jpg')
_FCapture = Image.open(_Img)
self.photo = ImageTk.PhotoImage(_FCapture)
self.C = Tk.Canvas(self, width=self.winfo_screenwidth(),
height=self.winfo_screenheight())
self.C.create_image(0, 0, image=self.photo, anchor=NW)
self.update()
self.Sccap.delete()
self.C.pack(fill=BOTH)
mainmenu = MainMenu(self, bg='white', fg='black', activefg='blue')
mainmenu.additem('Ligne', lambda e: self._Trace('ligne'))
mainmenu.additem('Rectangle', lambda e: self._Trace('rectangle'))
mainmenu.additem('Ovale', lambda e: self._Trace('ovale'))
mainmenu.additem('Texte', lambda e: self._Trace('texte'))
mainmenu.addctrl('Effacer', lambda e: self._Trace('delete'))
mainmenu.addctrl('Sauvegarder', lambda e: self.after(2, self._Save))
mainmenu.addctrl('Configurer', self.config)
mainmenu.addctrl("Réduire", self._Reduce)
self.bind('<Escape>', self._Intercepte)
self.bind('<3>', mainmenu.ShowMenu)
self.bind('<1>', self.addlist)
self.wm_attributes('-fullscreen', 1)
self.iconify()
def _Reduce(self, event=None):
self.iconify()
def addlist(self, event):
self._Pts.append((event.x, event.y))
if self._ToTrace == 'delete':
item = self.C.find_closest(event.x, event.y)
if item != (1,):
self.C.delete(item)
self._Clear()
elif self._ToTrace == 'ligne' and len(self._Pts) == 2:
self.C.create_line(self._Pts[0][0], self._Pts[0][1],
self._Pts[1][0], self._Pts[1][1],
fill=self.Color.get(),
width=self.Width.get())
self._Clear()
elif self._ToTrace == 'rectangle' and len(self._Pts) == 2:
self.C.create_rectangle(self._Pts[0][0], self._Pts[0][1],
self._Pts[1][0], self._Pts[1][1],
outline=self.Color.get(),
width=self.Width.get())
self._Clear()
elif self._ToTrace == 'ovale' and len(self._Pts) == 2:
self.C.create_oval(self._Pts[0][0], self._Pts[0][1],
self._Pts[1][0], self._Pts[1][1],
outline=self.Color.get(),
width=self.Width.get())
self._Clear()
elif self._ToTrace == 'texte':
for widget in (widget for widget in self.winfo_children()
if isinstance(widget, Tk.Toplevel)):
widget.destroy()
self.MenuText = Tk.Toplevel()
self.MenuText.title("Ajout d'un texte")
self.textentry = Tk.Entry(self.MenuText, width=80)
self.textentry.grid(row=0, column=0, columnspan=2, padx=5,
pady=5)
self.textentry.focus_set()
Tk.Button(self.MenuText, fg='green', text='Valider',
command=self._CreateTxt
) .grid(row=1, column=0, padx=5, pady=5)
Tk.Button(self.MenuText, fg='red', text='Annuler',
command=lambda: self._DelWidget(self.MenuText)
).grid(row=1, column=1, padx=5, pady=5)
self.MenuText.update()
self.MenuText.geometry("%dx%d+%d+%d" %
(self.MenuText.winfo_reqwidth(),
self.MenuText.winfo_reqheight(),
event.x, event.y))
self.MenuText.bind('<Escape>', lambda e:
self._DelWidget(self.MenuText))
def _DelWidget(self, widget):
widget.destroy()
self._Clear()
def _CreateTxt(self):
self.C.create_text(self._Pts[0][0], self._Pts[0][1],
fill=self.Color.get(), text=self.textentry.get())
self._DelWidget(self.MenuText)
# Cleaning
def _Clear(self):
self._ToTrace = None
del(self._Pts[:])
def _Intercepte(self, event=None):
self.quit()
# set self._ToTrace and clear self.Pts
def _Trace(self, obj):
del(self._Pts[:])
self._ToTrace = obj
def _Save(self, event=None):
"""Internal function"""
img = self.Sccap.grab(name='scrcap.jpg')
filetosave = tkFD.asksaveasfilename(initialdir=os.path.expanduser('~'),
title="Enregistrement",
filetypes=[('JPEG / JFIF','*.jpg')],
defaultextension='jpg',
initialfile='capture.jpg')
if filetosave:
if os.path.isfile(filetosave):
os.remove(filetosave)
os.rename(img, filetosave)
else:
self.Sccap.delete()
def config(self, event=None):
for widget in (widget for widget in self.winfo_children()
if isinstance(widget, Tk.Toplevel)):
widget.destroy()
self.MenuConfig = Tk.Toplevel()
self.MenuConfig.title("Configuration")
Tk.Label(self.MenuConfig, text='Epaisseur de ligne').grid(row=0,
column=0,
padx=5,
pady=5)
for i in range(0, 11):
Tk.Radiobutton(self.MenuConfig, text=str(i), variable=self.Width,
value=i).grid(row=1+i, column=0, padx=5, pady=5)
Tk.Label(self.MenuConfig, text='Couleur').grid(row=0, column=2,
padx=5, pady=5)
col = 0
for c, n in [('Noir', 'black'), ('Blanc', 'white'), ('Rouge', 'red'),
('Vert', 'green'), ('Bleu', 'blue'), ('Jaune', 'yellow'),
('Violet', 'purple'), ('Orange', 'orange'), ('Gris', 'gray'),
('Rose', 'pink'), ('Marron', 'brown'),]:
Tk.Radiobutton(self.MenuConfig, text=c, variable=self.Color,
value=n).grid(row=col+1, column=2, padx=5, pady=5,
sticky=W)
col += 1
Tk.Button(self.MenuConfig, fg='green', text='Quitter',
command=lambda: self._DelWidget(self.MenuConfig)
).grid(row=14, column=1, pady=10)
self.MenuConfig.bind('<Escape>', lambda e:
self._DelWidget(self.MenuConfig))
if __name__ == "__main__":
app = GUI(None)
app.mainloop() |
Partager