Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why do we use import * and then ttk in TKinter?
In tkinter applications, we use from tkinter import * to import all tkinter functions and classes, making them directly accessible without prefixes. However, for themed widgets with modern styling, we need to separately import the ttk module.
Understanding import *
The import * syntax imports all public functions and classes from the tkinter module into the current namespace:
from tkinter import * # Now you can use tkinter classes directly root = Tk() # Instead of tkinter.Tk() label = Label(root, text="Hello") # Instead of tkinter.Label()
Why Import ttk Separately?
The ttk (themed tkinter) module provides modern-looking widgets with native OS styling. It must be imported separately because it's a submodule:
from tkinter import * from tkinter import ttk # Regular tkinter button tk_button = Button(text="Old Style") # Modern ttk button ttk_button = ttk.Button(text="Modern Style")
Complete Example
Here's a functional application demonstrating both regular tkinter widgets and ttk widgets:
# Import tkinter library
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame or window
win = Tk()
# Set the geometry of tkinter frame
win.geometry("750x250")
# Define the function to change text
def change_text():
label.configure(text="Welcome")
# Create a label (regular tkinter widget)
label = Label(win, text="Click the below button to Change this Text",
font=('Arial', 16, 'bold'))
label.pack(pady=30)
# Create a button widget (ttk for modern styling)
button = ttk.Button(win, text="Commit", command=change_text)
button.pack()
win.mainloop()
Comparison of Approaches
| Import Method | Usage | Benefits |
|---|---|---|
from tkinter import * |
Direct access to all tkinter classes | Shorter syntax, less typing |
from tkinter import ttk |
Access to themed widgets | Modern appearance, native OS styling |
import tkinter as tk |
Explicit namespace | Cleaner code, avoids naming conflicts |
Key Differences: tkinter vs ttk Widgets
from tkinter import *
from tkinter import ttk
root = Tk()
root.geometry("300x150")
# Regular tkinter button (older style)
tk_button = Button(root, text="Tkinter Button")
tk_button.pack(pady=10)
# TTK button (modern themed style)
ttk_button = ttk.Button(root, text="TTK Button")
ttk_button.pack(pady=10)
root.mainloop()
Conclusion
Use from tkinter import * for easy access to basic widgets, and from tkinter import ttk for modern, themed widgets. The ttk module provides better visual appearance with native OS styling, making your applications look more professional.
