Key signature and chords by: Ido from www.piano-play-it.com
Hi, this is a very good question.
When a piece is written in C major, it means that the most stable chord in the piece is the C major chord. The piece might include many chords from different scales, but eventually, the last chord in the whole piece or song will be (in 99% of the cases) the basic chord of the piece - in C major scale it will be C major chord, in Eb major scale it will be the Eb major chord, etc.).
The basic scale of a piece is the place which you can define as your home, from which you can go and visit many other places but finally return back to your home base ? the basic scale.
So, if you see chords from different scales it means that the composer had chosen to lead you to other places, but in the end he will lead you back to your home sweet home.
In songs: The majority of songs include only chords which are of the basic scale, with just a few exceptions. In Rock, the song usually stays in the basic scale, while in Jazz there are many chords from other scales.
In classical pieces: Classical pieces include many chords which are not of this scale. Why? I think that you have answered this question. It would be very boring to listen to the same scale over and over again. In songs it is acceptable, but in artistic musical pieces one needs a variety of sounds. However, the chords which are not from the basic scale can be explained through the basic scale. Let's say that your piece is in C major. In this case C, Dm, Em, F, G, Am, Bo are all chords from the basic scale. What happens when you encounter the E chord? Of course, it is not a chord from the C major scale, but it has a strong relation to the C major scale. How? E is the Dominant chord of Am which is a chord from the basic scale. In other words it is a secondary dominant. The same happens with many other chords from different scales. They are not from the basic scale but they have a strong connection to it.
To summarize, A piece which is written in one scale usually includes chords from other scales in order to give a variety of sounds and to make the music interesting. The chords from the other scales can be explained through the basic scale. They are not just put there; they have a strong connection to the basic scale.
I hope that I have helped you, and I am here to answer any questions you may have.