为什么这个变量超出范围?

2024-06-25 23:13:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在使用函数后清空函数中的一个全局数组变量,但它显示它正在被隐藏,我不知道为什么。这是我的密码我做错什么了吗

import time
from tkinter import filedialog
import Main

attachments = []


def attach_file():
    filename = filedialog.askopenfilename(initialdir='C:/', title='Select a file')

    attachments.append(filename)
    print(attachments)

    if len(attachments) == 1:
        Main.notif.config(fg="green", text="Attached " + str(len(attachments)) + " file")
    elif len(attachments) > 1:
        Main.notif.config(fg="green", text="Attached " + str(len(attachments)) + " files")

    Main.root.update()
    time.sleep(1)

    Main.notif.config(text="")

    filename2 = attachments[0]
    filetype = filename2.split('.')
    filetype = filetype[1]

    if filetype == "jpg" or filetype == "JPG" or filetype == "png" or filetype == "PNG":
        print("Image")
    else:
        print("doc")

    attachments = [] <= error here

这是用于使用Tkinter、SMTP lib和email.message附加我的Gmail发件人应用程序的文件


Tags: or函数textimportconfiglentimemain
1条回答
网友
1楼 · 发布于 2024-06-25 23:13:44

a global array variable

您需要告诉Python它是一个全局变量:

def attach_file():
    global attachments # here

    filename = filedialog.askopenfilename(initialdir='C:/', title='Select a file')

    attachments.append(filename)

    # ...

    attachments = [] # no error anymore

相关问题 更多 >