You need to wrap your loop in a procedure and then call that procedure from the button in your UI. The procedure would be something like this:
Code:
global proc myShaveWriteProcedure()
{
insert loop here...;
}
The button would then get an extra flag:
Code:
button -c "myShaveWriteProcedure";
The window script will also need to be put into a procedure:
Code:
global proc myShaveWindow()
{
window stuff here...'
}
Save all this in a called myShaveWindow.mel and then you can run "myShaveWindow" from within Maya to bring up the window.