<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                從今年1月份開始學習python以來,一直寫一些很小的腳本文件,也主要是為了練習,今天花了些時間,寫了一個還算功能齊全的小程序,并完成單元測試、系統測試、及打包等工作。與任何商業軟件開發過程一樣,小程序從無都有,也必須經歷(需求分析、設計、編碼、單元測試、打包、系統測試、發布各階段),所以,借此,結合實現過程中遇到的問題,將此程序各環節做一個簡單介紹,算做筆記,如果能對讀者有所幫助,就再好不過了。 ### 一、需求分析: 1、標題: ?開發一個可以快速抓圖的小工具。 2、來源: 自己。 3、背景: 去年在工作中寫過三四次軟件操作指導書,step by step 的那種,這種指導書中難免會使用到各種操作界面的截圖,有時需要全屏圖片,有時需要當前窗口、更多時候需要 界面的部分圖片,且需要將重點處使用紅框做出標記,那時一直使用PrtSc鍵進行抓圖,然后在畫圖板中編輯一下,最后在貼在word中,操作步驟多且單調,一定程度影響了工作效率。(由于公司不能上QQ,所以QQ相當方便的截圖功能沒法使用。) 4、價值: 價值不大,網上應該有好多這樣的工具,但對個人學習python倒是很有幫助。 5、約束: 僅支持Windows環境上使用。 ### 二、設計: 不分什么概要設計和詳細設計了,簡單描述一下思路: 通過使用pyhk模塊提供的快捷鍵方式,注冊3個快捷鍵(CTRL+F1/F2/F3),分別對應抓取三種不同的圖片(全屏/當前窗口/任意區域),因用戶習慣不盡相同,所以程序需要提供需要鼠標操作方式,此程序不是時時都使用,所以不能讓它一直占用寬度有限的狀態欄資源,故需要做成托盤程序,在托盤圖標上通過鼠標右鍵點擊彈出菜單項來進行抓圖操作。 畫個簡單的圖: ![](https://box.kancloud.cn/2016-06-08_57579359e55d6.jpg) 圖1 用例圖 ### 三、編碼: 這一部分在前面的博文中已經講過,見[《Python:一個多功能的抓圖工具開發(附源碼)》](http://blog.csdn.net/dyx1024/article/details/7340903)和[《Python:程序最小化到托盤功能實現》](http://blog.csdn.net/dyx1024/article/details/7430638),今天對這個程序做了些改動,最主要的是將這兩個源碼結合起來,并修正一些測試中發現的問題,最終代碼如下,不再做詳細解釋。 1、screenshot.py ~~~ #!/usr/bin/env python #coding=gb2312 #此模塊主要提供抓圖功能,支持以下三種抓圖方式: #1、抓取全屏,快捷鍵CTRL+F1 #2、抓取當前窗口,快捷鍵CTRL+F2 #3、抓取所選區域,快捷鍵CTRL+F3 #抓到之后,會自動彈出保存對話框,選擇路徑保存即可 #*********************** #更新記錄 #0.1 2012-03-10 create by dyx1024 #********************** import pyhk import wx import os import sys from PIL import ImageGrab import ctypes import win32gui import ctypes.wintypes import screen_tray def capture_fullscreen(SysTrayIcon): ''' Function:全屏抓圖 Input:NONE Output: NONE author: socrates blog:http://blog.csdn.net/dyx1024 date:2012-03-10 ''' #抓圖 pic = ImageGrab.grab() #保存圖片 save_pic(pic) def capture_current_windows(SysTrayIcon = None): ''' Function:抓取當前窗口 Input:NONE Output: NONE author: socrates blog:http://blog.csdn.net/dyx1024 date:2012-03-10 ''' #窗口結構 class RECT(ctypes.Structure): _fields_ = [('left', ctypes.c_long), ('top', ctypes.c_long), ('right', ctypes.c_long), ('bottom', ctypes.c_long)] def __str__(self): return str((self.left, self.top, self.right, self.bottom)) rect = RECT() #獲取當前窗口句柄 HWND = win32gui.GetForegroundWindow() #取當前窗口坐標 ctypes.windll.user32.GetWindowRect(HWND,ctypes.byref(rect)) #調整坐標 rangle = (rect.left+2,rect.top+2,rect.right-2,rect.bottom-2) #抓圖 pic = ImageGrab.grab(rangle) #保存 save_pic(pic) def capture_choose_windows(SysTrayIcon): ''' Function:抓取選擇的區域,沒有自己寫這個,借用QQ抓圖功能 Input:NONE Output: NONE author: socrates blog:http://blog.csdn.net/dyx1024 date:2012-03-10 ''' try: #加載QQ抓圖使用的dll dll_handle = ctypes.cdll.LoadLibrary('CameraDll.dll') except Exception: try: #如果dll加載失敗,則換種方法使用,直接運行,如果還失敗,退出 os.system("Rundll32.exe CameraDll.dll, CameraSubArea") except Exception: return else: try: #加載dll成功,則調用抓圖函數,注:沒有分析清楚這個函數帶的參數個數 #及類型,所以此語句執行后會報參數缺少4個字節,但不影響抓圖功能,所 #以直接忽略了些異常 dll_handle.CameraSubArea(0) except Exception: return def save_pic(pic, filename = '未命令圖片.png'): ''' Function:使用文件對框,保存圖片 Input:NONE Output: NONE author: socrates blog:http://blog.csdn.net/dyx1024 date:2012-03-10 ''' app = wx.PySimpleApp() wildcard = "PNG(*.png)|*.png" dialog = wx.FileDialog(None, "Select a place", os.getcwd(), filename, wildcard, wx.SAVE) if dialog.ShowModal() == wx.ID_OK: pic.save(dialog.GetPath().encode('gb2312')) else: pass dialog.Destroy() class hook_kev_screenshot: def __init__(self): self.data = screen_tray.SysTrayIcon def capture_fullscreen(self): capture_fullscreen(self.data) def capture_current_windows(self): capture_current_windows(self.data) def capture_choose_windows(self): capture_choose_windows(self.data) def screenshot_main(): ''' Function:主函數,注冊快捷鍵 Input:NONE Output: NONE author: socrates blog:http://blog.csdn.net/dyx1024 date:2012-03-10 ''' #創建hotkey句柄 hot_handle = pyhk.pyhk() fun = hook_kev_screenshot() #注冊抓取全屏快捷鍵CTRL+F1 hot_handle.addHotkey(['Ctrl', 'F1'], fun.capture_fullscreen) #注冊抓取當前窗口快捷鍵CTRL+F2 hot_handle.addHotkey(['Ctrl', 'F2'], fun.capture_current_windows) #注冊抓取所選區域快捷鍵CTRL+F3 hot_handle.addHotkey(['Ctrl', 'F3'], fun.capture_choose_windows) #開始運行 hot_handle.start() ~~~ 2、screen_tray.py ~~~ #!/usr/bin/env python #coding=gb2312 #!/usr/bin/env python #coding=gb2312 #此模塊主要將程序最小化到托盤,并可使用托盤上的菜單進行抓圖操作 #同時提供快鍵鍵抓圖,各快鍵定義如下:: #1、抓取全屏,快捷鍵CTRL+F1 #2、抓取當前窗口,快捷鍵CTRL+F2 #3、抓取所選區域,快捷鍵CTRL+F3 #抓到之后,會自動彈出保存對話框,選擇路徑保存即可 #程序中使用到類SysTrayIcon,可從以下站點獲取: #http://www.brunningonline.net/simon/blog/archives/SysTrayIcon.py.html #*********************** #更新記錄 #0.1 2012-04-07 create by dyx1024 #********************** import os import sys import win32api import win32con import win32gui_struct import itertools, glob import screenshot try: import winxpgui as win32gui except ImportError: import win32gui class SysTrayIcon(object): '''TODO''' QUIT = 'QUIT' SPECIAL_ACTIONS = [QUIT] FIRST_ID = 1023 def __init__(self, icon, hover_text, menu_options, on_quit=None, default_menu_index=None, window_class_name=None,): self.icon = icon self.hover_text = hover_text self.on_quit = on_quit menu_options = menu_options + (('退出', None, self.QUIT),) self._next_action_id = self.FIRST_ID self.menu_actions_by_id = set() self.menu_options = self._add_ids_to_menu_options(list(menu_options)) self.menu_actions_by_id = dict(self.menu_actions_by_id) del self._next_action_id self.default_menu_index = (default_menu_index or 0) self.window_class_name = window_class_name or "SysTrayIconPy" message_map = {win32gui.RegisterWindowMessage("TaskbarCreated"): self.restart, win32con.WM_DESTROY: self.destroy, win32con.WM_COMMAND: self.command, win32con.WM_USER+20 : self.notify,} # Register the Window class. window_class = win32gui.WNDCLASS() hinst = window_class.hInstance = win32gui.GetModuleHandle(None) window_class.lpszClassName = self.window_class_name window_class.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW; window_class.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW) window_class.hbrBackground = win32con.COLOR_WINDOW window_class.lpfnWndProc = message_map # could also specify a wndproc. classAtom = win32gui.RegisterClass(window_class) # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow(classAtom, self.window_class_name, style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None) win32gui.UpdateWindow(self.hwnd) self.notify_id = None self.refresh_icon() #由于HOT KEY也要捕獲消息,故此處暫不處理,在HOT KEY中統一處理,否則快捷鍵無法注冊使用 #win32gui.PumpMessages() def _add_ids_to_menu_options(self, menu_options): result = [] for menu_option in menu_options: option_text, option_icon, option_action = menu_option if callable(option_action) or option_action in self.SPECIAL_ACTIONS: self.menu_actions_by_id.add((self._next_action_id, option_action)) result.append(menu_option + (self._next_action_id,)) elif non_string_iterable(option_action): result.append((option_text, option_icon, self._add_ids_to_menu_options(option_action), self._next_action_id)) else: print 'Unknown item', option_text, option_icon, option_action self._next_action_id += 1 return result def refresh_icon(self): # Try and find a custom icon hinst = win32gui.GetModuleHandle(None) if os.path.isfile(self.icon): icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE hicon = win32gui.LoadImage(hinst, self.icon, win32con.IMAGE_ICON, 0, 0, icon_flags) else: print "Can't find icon file - using default." hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION) if self.notify_id: message = win32gui.NIM_MODIFY else: message = win32gui.NIM_ADD self.notify_id = (self.hwnd, 0, win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP, win32con.WM_USER+20, hicon, self.hover_text) win32gui.Shell_NotifyIcon(message, self.notify_id) def restart(self, hwnd, msg, wparam, lparam): self.refresh_icon() def destroy(self, hwnd, msg, wparam, lparam): if self.on_quit: self.on_quit(self) nid = (self.hwnd, 0) win32gui.Shell_NotifyIcon(win32gui.NIM_DELETE, nid) win32gui.PostQuitMessage(0) # Terminate the app. def notify(self, hwnd, msg, wparam, lparam): if lparam==win32con.WM_LBUTTONDBLCLK: self.execute_menu_option(self.default_menu_index + self.FIRST_ID) elif lparam==win32con.WM_RBUTTONUP: self.show_menu() elif lparam==win32con.WM_LBUTTONUP: pass return True def show_menu(self): menu = win32gui.CreatePopupMenu() self.create_menu(menu, self.menu_options) #win32gui.SetMenuDefaultItem(menu, 1000, 0) pos = win32gui.GetCursorPos() # See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/menus_0hdi.asp win32gui.SetForegroundWindow(self.hwnd) win32gui.TrackPopupMenu(menu, win32con.TPM_LEFTALIGN, pos[0], pos[1], 0, self.hwnd, None) win32gui.PostMessage(self.hwnd, win32con.WM_NULL, 0, 0) def create_menu(self, menu, menu_options): for option_text, option_icon, option_action, option_id in menu_options[::-1]: if option_icon: option_icon = self.prep_menu_icon(option_icon) if option_id in self.menu_actions_by_id: item, extras = win32gui_struct.PackMENUITEMINFO(text=option_text, hbmpItem=option_icon, wID=option_id) win32gui.InsertMenuItem(menu, 0, 1, item) else: submenu = win32gui.CreatePopupMenu() self.create_menu(submenu, option_action) item, extras = win32gui_struct.PackMENUITEMINFO(text=option_text, hbmpItem=option_icon, hSubMenu=submenu) win32gui.InsertMenuItem(menu, 0, 1, item) def prep_menu_icon(self, icon): # First load the icon. ico_x = win32api.GetSystemMetrics(win32con.SM_CXSMICON) ico_y = win32api.GetSystemMetrics(win32con.SM_CYSMICON) hicon = win32gui.LoadImage(0, icon, win32con.IMAGE_ICON, ico_x, ico_y, win32con.LR_LOADFROMFILE) hdcBitmap = win32gui.CreateCompatibleDC(0) hdcScreen = win32gui.GetDC(0) hbm = win32gui.CreateCompatibleBitmap(hdcScreen, ico_x, ico_y) hbmOld = win32gui.SelectObject(hdcBitmap, hbm) # Fill the background. brush = win32gui.GetSysColorBrush(win32con.COLOR_MENU) win32gui.FillRect(hdcBitmap, (0, 0, 16, 16), brush) # unclear if brush needs to be feed. Best clue I can find is: # "GetSysColorBrush returns a cached brush instead of allocating a new # one." - implies no DeleteObject # draw the icon win32gui.DrawIconEx(hdcBitmap, 0, 0, hicon, ico_x, ico_y, 0, 0, win32con.DI_NORMAL) win32gui.SelectObject(hdcBitmap, hbmOld) win32gui.DeleteDC(hdcBitmap) return hbm def command(self, hwnd, msg, wparam, lparam): id = win32gui.LOWORD(wparam) self.execute_menu_option(id) def execute_menu_option(self, id): menu_action = self.menu_actions_by_id[id] if menu_action == self.QUIT: win32gui.DestroyWindow(self.hwnd) else: menu_action(self) def non_string_iterable(obj): try: iter(obj) except TypeError: return False else: return not isinstance(obj, basestring) def help_text(sysTrayIcon): ''' Function:顯示幫助文件 Input:even Output: Ture author: socrates blog:http://blog.csdn.net/dyx1024 date:2012-04-07 ''' help_info = ''' 使用指導 本工具提供抓圖功能(包括全屏、當前窗口、任意區域),且有兩種操作方式: 一、程序運行后,在桌面右下腳托盤圖標上點右鍵,選擇彈出的菜單項進行抓圖操作。 二、通過快捷鍵進行操作,各快捷鍵定義如下: 1、抓取全屏,快捷鍵CTRL+F1 2、抓取當前窗口,快捷鍵CTRL+F2 3、抓取所選區域,快捷鍵CTRL+F3 ''' win32api.MessageBox(0, help_info, "幫助信息") if __name__ == '__main__': ''' Function:主程序,提供托盤及快捷鍵操作兩種方式抓圖 Input:even Output: Ture author: socrates blog:http://blog.csdn.net/dyx1024 date:2012-04-07 ''' #托盤圖標所在位置 icon_file = os.path.join(os.getcwd(), "datafile\screenshot.ico") if os.path.exists(icon_file): icons = icon_file else: icons = os.getenv('WINDIR') + "\SYSTEM32\orange-install.ico" #托盤鼠標停留提示 hover_text = "多功能抓圖工具" #托盤右鍵菜單項 menu_options = (('抓取全屏(CTRL+F1)', icons, screenshot.capture_fullscreen), ('抓取當前窗口(CTRL+F2)', icons, screenshot.capture_current_windows), ('抓取所選區域(CTRL+F3)', icons, screenshot.capture_choose_windows), ('幫助', icons, help_text) ) #退出程序 def bye(sysTrayIcon): pass #設置托盤 SysTrayIcon(icons, hover_text, menu_options, on_quit=bye) #注冊快捷鍵 screenshot.screenshot_main() ~~~ ### 四、單元測試 我使用的IDE為Eclipse+pyDev,功能強大,操作簡單、可直接打斷點進行逐語句調試,過程不介紹了,貼張圖上來。 ![](https://box.kancloud.cn/2016-06-08_5757935a041c9.png) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?圖2 單元測試 ### 五、打包: ? 這一部分浪費時間較多,在之前的文章[《Python:程序發布方式簡介一(打包為可執行文件EXE)》](http://blog.csdn.net/dyx1024/article/details/7417610)中介紹了py2exe工具的所用,但如文章所述,打包出的exe文件有些動態庫是沒有被包含的,導致部分機器上執行失敗。本次使用了另一個python打包工具Pyinstaller,此工具簡單,只需要三步操作,可從[http://www.pyinstaller.org/](http://www.pyinstaller.org/)下載此工具。說一下操作步驟: ? ?1、解壓下載后的文件到任意目錄,如E:\pyinstaller-1.5.1。 ? ?2、執行Configure.py。 ? ?3、將開發的python程序,相關文件、ico圖標文件拷到E:\pyinstaller-1.5.1目錄下。 ? ?4、執行Makespec.py -F -w -X screen_tray.py,執行后生成規則文件screen_tray.spec,內容如下,可手動編輯。 ~~~ # -*- mode: python -*- a = Analysis([os.path.join(HOMEPATH,'support\\_mountzlib.py'), os.path.join(HOMEPATH,'support\\useUnicode.py'), 'screen_tray.py'], pathex=['E:\\pyinstaller-1.5.1']) pyz = PYZ(a.pure) exe = EXE( pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name=os.path.join('dist', 'screen_tray.exe'), debug=False, strip=False, upx=True, console=False , icon='screenshot_tray.ico') app = BUNDLE(exe, name=os.path.join('dist', 'screen_tray.exe.app')) ~~~ ? 5、執行>Build.py E:\pyinstaller-1.5.1\screen_tray/screen_tray.spec打包。 ? 6、成功后,在E:\pyinstaller-1.5.1\screen_tray\dist目錄下生成screen_tray.exe文件。 ? ?![](https://box.kancloud.cn/2016-06-08_5757935a1c26e.jpg) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?圖3 打包后的文件 ? 7、由于托盤程序需要使用一個ico圖標,這個文件我一直沒有辦法打包進exe,浪費很多時間后放棄,所以在軟件發布時在exe文件所在上目錄中建立了一個子目錄datafile,其中存放圖標,用戶也可替換為自己的,只要文件名不變就行。程序中也做了些容錯處理,如果目錄不存在,則從系統目錄下加載一個。如下: ~~~ #托盤圖標所在位置 icon_file = os.path.join(os.getcwd(), "datafile\screenshot.ico") if os.path.exists(icon_file): icons = icon_file else: icons = os.getenv('WINDIR') + "\SYSTEM32\orange-install.ico" ~~~ ? 8、Pyinstaller使用方便,不足之處是它打包的EXE文件比較大,所以這個小工具有9M大小。 ### 六、系統測試: ? 直接運行一下看看,依然上圖: ? ?1、執行screen_tray.exe,托盤顯示正常。 ? ?![](https://box.kancloud.cn/2016-06-08_5757935a322e7.jpg) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?圖4 托盤顯示測試 ? ? 2、菜單項目測試,正常。 ? ??![](https://box.kancloud.cn/2016-06-08_5757935a4353d.jpg) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?圖5 菜單項測試 ? ?3、抓取功能正常(快捷鍵及菜單項) ![](https://box.kancloud.cn/2016-06-08_5757935a577f7.jpg) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?圖6 抓圖功能測試(任意區域) 4、幫助菜單正常。 ?![](https://box.kancloud.cn/2016-06-08_5757935a77f74.jpg) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??圖7 幫助功能測試(任意區域) ?其他測試點就不一一寫了,累了。 ### 七、發布: ? ?好像沒地方發布,目前就我一個用戶。 ? ?連同源碼一并上傳到資源中,感興趣的朋友可以試用,全當學習交流哈~ ? ?地址:[http://download.csdn.net/detail/dyx1024/4206549](http://download.csdn.net/detail/dyx1024/4206549) ### 八、結束: ? 電腦前坐了一整天,去公園逛逛。 ? 歸來,附所拍照片一張,純屬娛樂,與本文無關~~ ?![](https://box.kancloud.cn/2016-06-08_5757935a8ff62.JPG)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看