首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python中定义变量

在python中定义变量
EN

Stack Overflow用户
提问于 2022-09-27 20:14:43
回答 1查看 67关注 0票数 -1

我试图在python中从pdf转换到word,所以我有两个函数--一个用于转换文件,另一个用于保存文件。我想知道如何在这两个函数中定义一个变量:在这里,我所写的是,docx_file给了我在转换函数中没有定义的错误。

代码语言:javascript
复制
def convert():
    try:
        pdf = fileEntry.get()
        cv = Converter(pdf)
        cv.convert(docx_file, start=0, end=None)
        cv.close()
        if docx_file is None:
            return
           
    except FileNotFoundError:
        fileEntry.delete(0,END)
        fileEntry.config(fg="red")
        fileEntry.insert(0,"Please select a pdf file first")
    except:
        pass
    
def save2word():

    docx_file = asksaveasfile(mode='w',defaultextension=".docx", filetypes=[("word file","*.docx"), ("text file","*.txt")])
    docx_file.write()
    docx_file.close()
    
    if docx_file is None:
        return
    
    print("saved")
    fileEntry.delete(0,END)
    fileEntry.insert(0,"pdf Extracted and Saved...")
EN

回答 1

Stack Overflow用户

发布于 2022-09-27 20:29:21

可以尝试声明一个空白变量。

代码语言:javascript
复制
docx_file = ""    
def convert():
    try:
        pdf = fileEntry.get()
        cv = Converter(pdf)
        cv.convert(docx_file, start=0, end=None)
        cv.close()
        if docx_file is None:
            return

或将变量设置为全局变量。

代码语言:javascript
复制
def convert():
    try:
        pdf = fileEntry.get()
        cv = Converter(pdf)
        cv.convert(docx_file, start=0, end=None)
        cv.close()
        global docx_file
        if docx_file is None:
            return
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73873350

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档