Difference between import tkinter as tk and from tkinter import

TkinterServer Side ProgrammingProgramming

In order to work with tkinter applications and widgets, we have to import the tkinter library in the environment. There are multiple ways to import the tkinter library in the notebook.

  • Using from tkinter import *
  • Using import tkinter as tk

The first method to import the tkinter library is the most common, as it comes with all the inbuilt methods or functions. In the general sense, we don’t have to explicitly override the method for the widgets. In this way, we can create the object of widgets just by using the widget constructor. It comes with all the modules defined in tkinter.

However, to save the major typing efforts, we import the tkinter library with some acronym further that can be used to create an instance of widgets. Thus, the application structures become more aesthetical by using the import tkinter as tk.

The major difference between both the ways is, if we want to define the widget constructor explicitly by defining which module it is associated with, then we can use the acronym method. However, if we want to define every widget by importing all the functions and modules in it, then we can use "from tkinter import *" method.

Example

import tkinter as tk
win= Tk()
win.geometry("750x250")
entry= Text(win, width= 24)
entry.insert(INSERT,"Hello World!")
entry.tag_add("start","1.0","end")
entry.tag_configure("start", background="blue", foreground= "white")
entry.pack()
win.mainloop()

Output

The above code would flash an error. Now, replace the first line "import tkinter as tk" with "from tkinter import *" to import all the functions and modules in the environment. You will now get to see the following output window −

raja
Published on 15-Apr-2021 13:21:47
Advertisements