0

I want to empty a global array variable in a function after using it but it shows that it is being shadowed and I don't know why. Here is my code am I doing something wrong?

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

This is for attaching files of my Gmail sender app using Tkinter, SMTP lib, and email.message

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
YamiAtem
  • 132
  • 1
  • 9

1 Answers1

1

a global array variable

You need to tell Python that it's a global variable:

def attach_file():
    global attachments # here

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

    attachments.append(filename)

    # ...

    attachments = [] # no error anymore
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 2
    This true but you should avoid global variables in general https://stackoverflow.com/questions/19158339/why-are-global-variables-evil – BeanBagTheCat Jan 29 '21 at 17:04