import_example.py ... if you scour the internet for snippets of tkinter code you’ll see various methods for importing the library, like ‘import tkinter’ (rare), ‘import tkinter as Tk’ or, most common, ‘from tkinter import *’. So here seems like a good place to demonstrate the advantages and pitfalls of various methods. I used the ‘random’ library in the example because we’re already familiar with it. The code in this program shows four ways to import and three of them can cause a fail, especially ‘from random import *’. So run it per the instructions, with each of the four blocks active in different runs, and make sure you understand why it fails.
At the very bottom I’ve linked to Python style guides which tell your what to use. Note that I am not doing what they say, sticking with ‘from tkinter import *’ ... you can get away with that in small programs, or even large programs if you know what every variable and function is called. Where you typically have problems is on a large project where many people are writing code and some guy who wants to be ‘creative’ overwrites a library function name.
Student project: take the ‘sg_welcome.py’ program (above) and change the import to “import tkinter”. Then run it. It will fail. Now fix it ... good practice. One hint, the last line, mainloop() becomes root.mainloop() ... you can figure out the rest ...
Be careful checking this in an IDE other than IDLE. When I changed to “import tkinter” in my basic IDE (PyScripter) nothing bad happened. It ran clean. This blew my mind. Then I commented out the import statement and still ran fine. Wow, what is this? So I tried it in IDLE and of course it failed early and often, so check your solution in IDLE.
It seems my IDE supports “Remote TK” and TK is the underlying library for tkinter, so I didn’t even need to call the library. Took a while to track this down. If you have a fairly robust IDE then it’s possible you are also using the “Remote TK”. So if you don’t see any fails in your IDE, especially if you know it should fail, then check it in IDLE.
Student project # 2: remember when we discussed the ‘try – except’ error checking? How would you use this to automatically switch between ‘tkinter’ and ‘Tkinter’ (V3 vs V2) at the top of the programs? Mull this over, post your solutions below (it’s easy) and from now on we’ll use that construct so those running V2.x won’t have to make an edit to run these programs.