Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between import tkinter as tk and from tkinter import

Tags:

I know it is a stupid question but I am just starting to learn python and i don't have good knowledge of python. My question is what is the difference between

from Tkinter import * 

and

import Tkinter as tk 

?Why can't i just write

import Tkinter 

Could anyone spare a few mins to enlighten me?

like image 319
Chris Aung Avatar asked Apr 12 '13 15:04

Chris Aung


People also ask

Is tkinter same as Tk?

Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit, and is Python's de facto standard GUI. Tkinter is included with standard Linux, Microsoft Windows and macOS installs of Python. The name Tkinter comes from Tk interface.

What does from tkinter import * mean?

The significance of "import *" represents all the functions and built-in modules in the tkinter library. By importing all the functions and methods, we can use the inbuilt functions or methods in a particular application without importing them implicitly.

What is Tk from tkinter?

Tk is the original GUI library for the Tcl language. Tkinter is implemented as a Python wrapper around a complete Tcl interpreter embedded in the Python interpreter. There are several other popular Python GUI toolkits. Most popular are wxPython, PyQt, and PyGTK.

What does from tkinter import TTK mean?

ttk is a module that is used to style the tkinter widgets. Just like CSS is used to style an HTML element, we use tkinter. ttk to style tkinter widgets.


1 Answers

from Tkinter import * imports every exposed object in Tkinter into your current namespace. import Tkinter imports the "namespace" Tkinter in your namespace and import Tkinter as tk does the same, but "renames" it locally to 'tk' to save you typing

let's say we have a module foo, containing the classes A, B, and C.

Then import foo gives you access to foo.A, foo.B, and foo.C.

When you do import foo as x you have access to those too, but under the names x.A, x.B, and x.C. from foo import * will import A, B, and C directly in your current namespace, so you can access them with A, B, and C.

There is also from foo import A, C wich will import A and C, but not B into your current namespace.

You can also do from foo import B as Bar, which will make B available under the name Bar (in your current namespace).

So generally: when you want only one object of a module, you do from module import object or from module import object as whatiwantittocall.

When you want some modules functionality, you do import module, or import module as shortname to save you typing.

from module import * is discouraged, as you may accidentally shadow ("override") names, and may lose track which objects belong to wich module.

like image 187
ch3ka Avatar answered Sep 18 '22 12:09

ch3ka