Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Alert!

Tkinter question what does {if __name__ == '__main__':} without brackets mean in python Tkinter module ?

what does this does in python .

1 Answer

Hi there!

Not done much tkinter ( followed ONE guide on making a calculator lol) but this isn't so much a tkinter thing as it is a python thing.

You know how in python we write everything in modules, and import those modules into other modules to string them all together to make a program that isn't one really long confusing file, but lots of nice little organised ones? Well, you can also pick and choose just some of the modules to use in a different program without writing them all again.

What

if __name__ == '__main__':

Does is make sure that any code inside that if statement will only run if this is the module you are executing. That frees you up to import that module into any other project you're making and use all it's functions and classes without code inside the if statement being executed.

This happens because when you import a module in python, you're basically inserting that file into the current one to make one giant file for python to run through. So say you made a dice game with a load of random chance functions in it followed by the game code, and you wanted to use some of those random chance functions in your next game, if you imported the module as is, the whole dice game will run when python gets to those lines in the imported module. However, if you have the if __name __ == '__main __' block around the game code in your dice game, then that code would only run if that was the file you ran (by double clicking it, typing "python dicegame.py in the console, etc), not just if it is imported into another python file.

Basically, when you run a python file, the file you run has it's __name __ property set to '__main __', so you're just checking that this is the file that was originally executed, not just one that was imported, and if it is, do the following code.