繁体   English   中英

在 python 中定义变量

[英]defining variable in python

我正在尝试制作一个从 pdf 到 python 中的单词的小转换器,所以我有两个功能,一个用于转换文件,一个用于保存文件。 我想知道如何在这两个函数中定义一个变量:在这里我写的是, docx_file给了我在转换 function 中未定义的错误。

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...")

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

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

或将变量设置为全局

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM