Python Forum
confusion using the import statement
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
confusion using the import statement
#1
What is the differences between the following statements?
1)  import tkinter
2)  import tkinter as tk
3)  from tkinter import *
4)  from tkinter import font as tkFont
Reply
#2
It's not good practice to use wild cards. It might interfere with other modules or system functions.
I do the import tkinter as tk so I am not typing the full tkinter word. The same goes for me importing methods/functions from the modules. from some module import a_really_long_module_name as short_name
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
I need more clarification.

Does line 1 and 3 import all of the tinker module? Or, is line 1 and 3 the same thing?

By using the as word does this mean that I can reference tkinter.font or tk.font as the same thing?


what does line 2 do? Does this sort of rename the modules in tkinter as tk?
does line 4 only import font from tkinter and name it tkfont?
Reply
#4
import creates a module variable.
import tkinter

print(tkinter)
Output:
<module 'tkinter' from 'C:\\Program Files\\Python38\\lib\\tkinter\\__init__.py'>
Now you can use the new tkinter module variable to access the module attributes.

from module import name creates a new variable that references the imported part
from tkinter import Frame

print(Frame)
Output:
<class 'tkinter.Frame'>
When you do "from tkinter import *" you create a variable for each attribute in tkinter. And there are a lot of attributes, most of which you know nothing about.
import tkinter

print(len(dir(tkinter)))
Output:
160
"from tkinter import *" creates 160 variables in my program and I don't know the name of half of them. At the point you are in your programmer development you don't know most of them. You won't know if the variable you just created ends up breaking something in tkinter because the variable name is the same as a tkinter attribute.
Reply
#5
I get it I thnk
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020