import tkinter vs from tkinter import *

However, it won’t make more of a difference in most of the cases, but one can easily come across some scenarios where you’ll have to cognitively choose between import tkinter and from tkinter import *

1.import tkinter

Pros : 

  • You can access all contents of the module using the module name as a prefix.
  • You can avoid naming conflicts by using the module name to qualify the imported names

Cons:

  • You need to use the module name as a prefix, which can make your code more verbose.
  • If the module has a large number of contents, it can be cumbersome to access them all using the module name
import tkinter as tk 

root = tk.Tk()                    # Create the main application window 
root.title("Basic Tkinter Window")# Set the window title 
root.geometry("300x200")          # Set the window size

 

2. from tkinter  import *

Pros : 

  • You can access all contents of the module directly without using the module name as a prefix.
  • Your code can be more concise and easier to read.

Cons:

  • You can introduce naming conflicts if the module has names that collide with your local variables or other imported modules.
  • It can be harder to track where the imported names come from, making your code less readable and maintainable
from tkinter import *


root=Tk() 
mylabel = Label(root,text="hello ")
mylabel.pack()
root.mainloop()

Usually the best practice is to use import tkinter as tk and later on use whatever functions you are willing to use with the suffix. Though from tkinter method can also be used when you only want a single function from that module, in this case using the suffix doesn’t really makes sense.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top