1

So I see codes that look like this:

from Tkinter import *    
def main():
        root = Tk()
        root.geometry("250x150+300+300")
        root.title("GUI")
        root.mainloop()

But why do they write it in a function? Couldn't you do the same thing by typing this

from Tkinter import *
root = Tk()
root.geometry("250x150+300+300")
root.wm_iconbitmap(r'c:/Python33/DLLs/txteditor.ico')
app = txtEditor(root)
root.mainloop()

Not sure if this is considered a "good" question if not I understand I will remove it. But I am somewhat new to Python and just see this a lot but do not understand why? Any help would be appreciated :-)

2 Answers2

0

Occasionally it is useful to import a script so that you can test, or even use, some of the functions that are in it. If your main functionality is in a function this is easy to do.

However, if simply importing the script also executes the main functions -- well, that's not very useful.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
0

The main purpose of wrapping codes in a predefined function name (main in your case) is that, when your file gets imported by its parent script thus defined function is used as the entry point.

As said by Ethan Furman, the code wrapped in a function can be called only when needed where as the code scattered outside a function (your second example) gets executed right after it is imported.

Besides, your first snippet is much cleaner and self explanatory than the second one.

Asur
  • 1,949
  • 4
  • 23
  • 41
  • Thanks for the explanation! But what do you mean when your file gets imported by its parent script? Sorry for the beginner questions but I was just wondering –  May 22 '14 at 02:53
  • Suppose your above code is in `tinker_app.py`, looking at the name of the entry point function (`main`) it is first imported by other script, suppose `tinker_loader.py`. In this case `tinker_loader.py` is parent script or better even if called main script. – Asur May 22 '14 at 03:01
  • Follow this link http://stackoverflow.com/questions/419163/what-does-if-name-main-do, little different from your scenario but should satisfy your curiosity. – Asur May 22 '14 at 03:05