WinEunuuchs2Unix
WinEunuuchs2Unix

Reputation: 1947

Import tkinter/Tkinter as "Tk" or "tk"?

I've seen the light an will now convert all my tkinter references from Canvas to Tk.Canvas, from Label to tk.Label, and from root = Tk() to root = tk.Tk(), etc.

Stuck in between Python 2.7.12 and Python 3.5 my program stub looks like this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
    import tkinter as Tk
    import tkinter.ttk as ttk
    import tkinter.font as font
except ImportError: # Python 2
    import Tkinter as Tk
    import ttk
    import tkFont as font

The question is should I be using import tkinter as Tk or import tkinter as tk?

I'm thinking the latter but I would like to stick to industry standards. Also take into consideration how most answers are written in Stack Overflow. Going with this majority means I can try code snippets with the least modifications.

The advantage I see using import tkinter as tk is:

I'm still on my first Python project and want to develop good reusable code for future projects.

Upvotes: 0

Views: 1428

Answers (2)

Ishita Pathak
Ishita Pathak

Reputation: 61

In Python 3, you generally import tkinter and use Tk This syntax is used to avoid potential naming conflicts in your code. It imports the tkinter module and renames it to tk for convenience. Then, you use tk.Tk() to create an instance of the Tk class.

import tkinter as tk
top = tk.Tk()

If you're using Python 2, you would import it as Tkinter and use Tk

import Tkinter as tk
top = tk.Tk()

Upvotes: 1

Bryan Oakley
Bryan Oakley

Reputation: 386382

The question is should I be using import tkinter as Tk or import tkinter as tk?

You should use import tkinter as tk, based on the naming conventions in pep8

Upvotes: 5

Related Questions