V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
qile1
V2EX  ›  Python

我照网上写了一个最小化到桌面的程序,直接运行不报错,但是用 cxfreeze 编译后报 ImportError: No module named 'pywintypes'错,麻烦帮忙看看 python3.5.2 win7 32 位系统

  •  
  •   qile1 · 2016-11-20 17:53:17 +08:00 · 4583 次点击
    这是一个创建于 2923 天前的主题,其中的信息可能已经有所发展或是发生改变。

    python3.5.2 win7 32 位系统,直接运行可以,编译成 exe 报这错误

        ---------------------------
        Traceback (most recent call last):
          File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35-32\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 12, in <module>
          File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35-32\lib\site-packages\cx_Freeze\initscripts\Console.py", line 21, in <module>
          File "D:\test\sysTRyIco3.py", line 6, in <module>
          File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35-32\lib\site-packages\win32\lib\win32gui_struct.py", line 36, in <module>
        ImportError: No module named 'pywintypes'
    

    源代码如下:

    # _*_ coding: utf-8 _*_
    import os
    import sys
    import win32api
    import win32con
    import win32gui_struct
    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 + (('QUIT', 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()
            
            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)#python2.7 user
            return not isinstance(obj, (str))
        
        
        
    
    # Minimal self test. You'll need a bunch of ICO files in the current working
    # directory in order for this to work...
    
    import itertools, glob
    
    icons = itertools.cycle(glob.glob('*.ico'))
    hover_text = "com1 9600 n 8 1 \n load:902"
    print (glob.glob('*.ico'))
    def hello(sysTrayIcon): print ("Hello World.")
    def simon(sysTrayIcon): print ("Hello Simon.")
    def rehandle(sysTrayIcon): print ("rehandling......")
    def switch_icon(sysTrayIcon):
        sysTrayIcon.icon = icons.__next__()
        sysTrayIcon.refresh_icon()
    menu_options = (('Say Hello', icons.__next__(), hello),
                    ('Switch Icon', None, switch_icon),
                    ('rehandle',icons.__next__(), rehandle),
                    ('A sub-menu', icons.__next__(), (('Say Hello to Simon', icons.__next__(), simon),
                                                  ('Switch Icon',icons.__next__(), switch_icon),
                                                 ))
                   )
    def bye(sysTrayIcon): print ('Bye, then.')
    print (os.path.abspath(os.curdir))
    print (sys.argv[0])
    SysTrayIcon(icons.__next__(), hover_text, menu_options, on_quit=bye, default_menu_index=1)
    #print (os.getcwd())
    #SysTrayIcon(icons.next(), hover_text, menu_options, on_quit=bye, default_menu_index=1)
    
    
    #cxfreeze  D:\test\sysTRyIco3.py  --target-dir D:\runexe --base-name=Win32GUI
    
    5 条回复    2016-11-25 14:11:11 +08:00
    xenme
        1
    xenme  
       2016-11-20 19:31:29 +08:00 via iPhone
    都直接用 win32 api 了,为啥不直接 C 呢
    faketemp
        2
    faketemp  
       2016-11-23 14:11:34 +08:00 via iPhone
    把主 py 脚本和图标、编译脚本等文件全部放到 python35/LIB 中 再编译就行了
    qile1
        3
    qile1  
    OP
       2016-11-24 08:10:06 +08:00
    @faketemp
    我把程序放到安装目录下面,运行还是提示 ImportError: No module named 'pywintypes'
    C:\Users\Administrator>cxfreeze C:\Users\Administrator\AppData\Local\Programs\Python\Python35-32\Lib\sysTRyIco3.py --target-dir D:\runexe --base-name=Win32GUI

    ---------------------------
    cx_Freeze: Python error in main script
    ---------------------------
    Traceback (most recent call last):
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35-32\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 12, in <module>
    __import__(name + "__init__")
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35-32\lib\site-packages\cx_Freeze\initscripts\Console.py", line 21, in <module>
    scriptModule = __import__(moduleName)
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35-32\Lib\sysTRyIco3.py", line 6, in <module>
    import win32gui_struct
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35-32\lib\site-packages\win32\lib\win32gui_struct.py", line 36, in <module>
    import pywintypes
    ImportError: No module named 'pywintypes'

    ---------------------------
    确定
    ---------------------------

    请问下编译脚本 在哪里找到,我直接 cxfreeze 运行的
    faketemp
        4
    faketemp  
       2016-11-24 15:53:09 +08:00 via iPhone
    试试 pyinstaller 或者 py2exe 吧 cx_Freeze 错误太多了
    qile1
        5
    qile1  
    OP
       2016-11-25 14:11:11 +08:00 via Android
    pyinstaller 试过,报错更多, py2exe 没试,我一会试试, python2.7 我打包没问题, python3.5 我修改的程序报那个错,在另一台笔记本上面也报同样错,主要想实现右下角图标菜单显示, python 有没有其他只显示有下角图标的程序
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3052 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 13:52 · PVG 21:52 · LAX 05:52 · JFK 08:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.