How to use win32com.client.constants with MS Word?

空扰寡人 提交于 2019-12-23 16:15:51

问题


Whats wrong with this code? Why win32com.client.constants doesn't have attribute wdWindowStateMinimize?

>>> import win32com.client
>>> w=win32com.client.Dispatch("Word.Application")
>>> w.WindowState = win32com.client.constants.wdWindowStateMinimize
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    w.WindowState = win32com.client.constants.wdWindowStateMinimize
  File "C:\Python34\lib\site-packages\win32com\client\__init__.py", line 170, in __getattr__
    raise AttributeError(a)
AttributeError: wdWindowStateMinimize`

回答1:


You must use EnsureDispatch instead:

>>> w=win32com.client.gencache.EnsureDispatch('Word.Application')
>>> win32com.client.constants.wdWindowStateMinimize
2
>>>

Note that the first time you use EnsureDispatch on a particular COM server, pywin32 generates the COM type lib for it (Word in your case), so it can take many seconds. For Excel, it took almost 30 seconds. But after that, the dispatch is quick, and you can even use the regular Dispatch (so you could code your app to use Dispatch, which is faster than EnsureDispatch, and check if the constant is defined, and if not, the code uses EnsureDispatch).

See my answer to this other post for more details.



来源:https://stackoverflow.com/questions/28264548/how-to-use-win32com-client-constants-with-ms-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!