You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python操作LibreOffice:关闭文档后调用MsgBox报getCurrentController属性错误

问题解决:LibreOffice UNO MsgBox 报错“object has no attribute getCurrentController”

问题描述

  • 复现步骤:
    1. 打开已存储文档,保存后调用MsgBox,关闭该文档;
    2. 新建文档并再次调用MsgBox,出现“object has no attribute getCurrentController”错误。
  • 已尝试操作:将窗口目标从_default改为_blank,添加3秒延迟,问题仍未解决。

错误原因

原MsgBox函数依赖desktop.getCurrentComponent()获取当前文档,但在文档关闭、新建的时序中,LibreOffice桌面组件可能未及时更新当前激活的文档对象,导致getCurrentComponent()返回无效对象,进而调用getCurrentController()时出错。

解决方案

修改MsgBox函数,直接传入要绑定的文档对象,而非依赖自动获取当前组件。这样能确保弹窗始终绑定到指定文档窗口,避免时序问题。

修改后的完整代码

import uno, os, time
from com.sun.star.beans import PropertyValue

def MsgBox(doc, message):
    ctx = uno.getComponentContext()
    sm = ctx.getServiceManager()
    # 直接使用传入的文档对象获取控制器
    oDocController = doc.getCurrentController()
    oToolkit = sm.createInstance('com.sun.star.awt.Toolkit')
    msgbox = oToolkit.createMessageBox(
        oDocController.getFrame().getContainerWindow(),
        "infobox",
        1,
        "LibreOffice",
        str(message)
    )
    msgbox.execute()
    msgbox.dispose()
    return

def documento_1():
    ctx = uno.getComponentContext()
    sm = ctx.getServiceManager()
    desktop = sm.createInstanceWithContext('com.sun.star.frame.Desktop', ctx)
    opciones = []
    
    opcion = PropertyValue()
    opcion.Name = 'As Template'
    opcion.Value = False
    opciones.append(opcion)
    
    # 重新创建PropertyValue对象,避免属性覆盖
    opcion = PropertyValue()
    opcion.Name = 'Password'
    opcion.Value = 'letmein'
    opciones.append(opcion)
    
    ruta = uno.systemPathToFileUrl('/home/jaguar/Documentos/Untitled 1.odt')
    
    # 第一个文档
    doc = desktop.loadComponentFromURL(ruta, '_blank', 0, tuple(opciones))
    MsgBox(doc, doc.hasLocation())

    doc.store()
    doc.close(True)
    
    # 第二个新文档
    doc1 = desktop.loadComponentFromURL('private:factory/swriter', '_blank', 0, ())
    MsgBox(doc1, doc1.hasLocation())
    doc1.close(True)
    return

关键修改点

  • MsgBox参数调整:新增doc参数,直接传入目标文档对象,摆脱对desktop.getCurrentComponent()的依赖,避免对象获取不稳定的问题。
  • 修复PropertyValue复用问题:原代码重复使用同一个opcion对象,会导致属性被覆盖,改为重新创建新的PropertyValue对象设置密码属性。
  • 移除冗余延迟:通过绑定指定文档,无需再依赖延迟等待组件更新,代码更高效可靠。

内容的提问来源于stack exchange,提问作者Daniel Hernandez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 21:20:17