what is the best way to import in Tkinter module?

Question:

# first way 
import tkinter
# second way 
from tkinter import *

The best way to import methods in tkinker module

Asked By: Mohamed Khaled

||

Answers:

import tkinter is the normal, standard way of importing things. If you use that and you want to use the Frame class from the tkinter module, then you would use variable = tkinter.Frame().

Sometimes, we only need a single thing from a module. If we only need the Frame class, we could use from tkinter import Frame. That way we could use it like this: variable = Frame(). This saves us a tiny bit of typing.

A wildcard import like from tkinter import * imports everything that tkinter offers. So we can again use variable = Frame() and save a bit of typing.

Wildcard imports are used in example code a lot because they make the example shorter and clearer. But you should never use them in real code. They lead to bugs and are against PEP8. You should use a normal import.

There is another trick to save some typing: an alias. The import would be import tkinter as tk, and then you could use it with variable = tk.Frame(). This is the import that you will see most often for tkinter.

From the computer’s point of view, all of these imports are exactly the same. None of them is any faster or more efficient than the other. They are all just for the programmers convenience.

Answered By: Novel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.