ModuleNotFoundError: No module named 'Tkinter' in python using python 3 [duplicate] - python

This question already has answers here:
ImportError: No module named 'Tkinter'
(27 answers)
Closed 5 years ago.
I get the error ModuleNotFoundError: No module named 'Tkinter' in Python 3. I am trying to run this piece of code.
from swampy.TurtleWorld import *
import Tkinter
world = TurtleWorld()
bob = Turtle()
fd(bob, 100)
lt(bob)
fd(bob, 100)
print (bob)
wait_for_user()

It doesn't look like your code is using Tkinter at all, so you could just remove the line import Tkinter. In any case, you should be able to import Tkinter in Python always, because it is built into the standard library; the problem is that the module is named tkinter in lowercase, not Tkinter, so it should be:
import tkinter
But again, if you are not going to use the module it would be clearer to remove that import statement.

The way you are importing Tkinter uses the capitalization for Python 2. In Python 3 Tkinter has a lower case 't'. So for Python 3 you would write it as:
import tkinter
To make their programs work in both Python 2 and Python 3 I have seem many people write their code in the following manner:
try:
import Tkinter
except:
import tkinter
With the above you will have the correct import for whether you or not you are using Python 2 or Python 3. I'd also recommend setting up as value for tkinter such as:
import tkinter as tk
This way while you are programming instead of writing tkinter.Frame() you can shorten it to tk.Frame(). It makes it a lot quicker to code Tkinter programs.
I am assuming you are planning on implementing Tkinter later in your code as currently your code makes no use of it, so I hope this helps. If you are not going to add anything using Tkinter, I would recommend removing the import.

Related

from tkinter import * showing SyntaxError when used inside function

Here I am using from tkinter import * inside a function and when I am running the code it is showing me a SyntaxError.
Please tell me how I can use from tkinter import * inside a function.
You should move the import statements to the beginning of the file, at the top. You are also importing tkinter twice.

What's the difference between these two [duplicate]

This question already has answers here:
Difference between import tkinter as tk and from tkinter import
(3 answers)
How do I import other Python files?
(23 answers)
Closed 4 years ago.
Can someone please explain the difference between
import tkinter as tk
and
from tkinter import *
It would be so great if someone could give and example where the same task is
achieved (or an object is created) by using these two statements seperately
Simply saying, the import tkinter as tk will initiate a tk instance of tkinter in your file which can call it's functions by writing something like
tk.Entry()
Which will save you from typing the long name.
while from tkinter import * will import all the names defined under the __all__ variable, so you can call the same function as
Entry()
You should read This to understand more
Both are importing the same package. The primary difference is that your first line is importing the package tkinter and then referring to it with "tk", which would allow you to call its functions using that different name. I don't have any experience with tkinter, but a good example I can give would be with numpy or pandas. A lot of functions in numpy, like numpy.random.randn() could instead be written with a shorthand name using "import as", like so:
import numpy as np
np.random.randn()
The differences seams little at first however import tkinter as tk is actually a much better option for one big reason.
By importing as something specific you make all the methods from that import required a prifix. This prevents methods from overriding or being overwritten accidentally.
For example if I have a library that contains a time() method and say lest call this library custom_timer and then say I need to import the built in time method also.
If use * for my import we have a problem.
from custom_timer import * # importing all modules including time() form this library.
import time # importing built in time().
What will end up happening is the 2nd import will override the time method from the first import. To prevent accidents like this we can simple import as your_prefix_here.
Take this example.
import custom_timer as ct # importing this library as ct.
import time # importing built in time().
In this case we will have 2 distinctive imports for time that do not override each other.
One is ct.time() and the other is time()
Because libraries like tkinter contain many methods it is safer to use import as verses import * for the above reason.
All that said if you are in a hurry and just want to throw something together to test an idea or answer a question using from tkinter import * is fine for much smaller applications. Personally I try to use import tkinter as tk for everything I do for good practice.
As for your request for 2 examples see below.
With tk import:
import tkinter as tk
root = tk.Tk()
tk.Label(root, text="I am a label made using tk prefix.")
root.mainloop()
With * import:
from tkinter import *
root = Tk()
Label(root, text="I am a label made in tkinter with the * import.")
root.mainloop()

What is the correct way to arrange unwieldy imports

I'm fairly new to python and looking for the best (most preferred) way to handle imports in a project.
I've been given the task to cleanup a python project and noticed there are the same includes in many modules throughout the project. Here is an example of what I am seeing.
File my_main_file.py
import os
import sys
import inspect
...
import gvars
import Common
...
from Tkinter import Menu
from Tkinter import WORD
from Tkinter import END
from Tkinter import Text
...
import menus.config
File gvars.py (also calls Tkinter)
from Tkinter import Text
from Tkinter import Tk
import Tkinter
File Common.py (also calls gvars and os)
import gvars
import tkFileDialog
import os
From Menus/config.py (also calls Common, gvars and Tkinter)
import Common
import gvars
import UIFunctions
import Tkinter
# Imports from Tk
from Tkinter import END
from Tkinter import Toplevel
from Tkinter import Button, Checkbutton
from Tkinter import Label
And on and on it goes... As you can see this is a mess I inherited. I know there are issue here (like "import blah" followed by "from blah import yuck"). I'm just looking for the most pythonic way to handle this.
Do I only need the imports in my_main_file.py? I.e. will Common.py code be able to access os. methods if "import os" is removed from the module and i=is only in the main script.
Is it best to have imports that are only referenced in a module imported in that module even though they are the similar? I.e. "from Tkinter import Text" in one module and "from Tkinter import END" in another.
Side question - which is better?
import Tkinter
or
from Tkinter import Menu
from Tkinter import WORD
from Tkinter import END
from Tkinter import Text
from Tkinter import Scrollbar
from Tkinter import Toplevel
from Tkinter import Button, Checkbutton
from Tkinter import Label
from Tkinter import Entry
from Tkinter import LEFT, RIGHT, TOP, BOTTOM
from Tkinter import DISABLED
from Tkinter import X, Y, BOTH
from Tkinter import VERTICAL, HORIZONTAL
from Tkinter import Listbox
from Tkinter import Frame, LabelFrame
from Tkinter import Entry
from Tkinter import N,S,E,W
from Tkinter import BROWSE, EXTENDED
from Tkinter import DISABLED, NORMAL
According to the PEP8 styleguide (one of the most authoritative sources on what is pythonic) using wildcard imports (from ... import *) should be avoided unless you are republishing an interface, which is not your intent.
My suggestion is to import TKinter as tk and refer to tk.WORD etc.
One of the reasons for doing this is that some of the constants and classes from Tkinter are fairly generically named - N, Button, etc.
By referring to tk.N, tk.Button, etc. it makes your intent in the code much clearer.
If one or two specific things are imported, then:
from Tkinter import END, Toplevel, ...
If pretty much everything in that module is imported, then:
from Tkinter import *
If more than a bunch of functions and classes are imported, then:
import Tkinter
Or more pythonic:
import Tkinter as tk
I am not sure if we can have common file to import all common modules. I think, for all of the files which you mentioned in question, you need to have separate imports.
About your side question, it is better to import specific function, method from class. You should import only those methods, functions which are being used in file. if you just do import Tkinter, then you have to use it like Tkinter.Menu, Tkinter.WORD etc in your code. Then it might be difficult to read if some library or module's functions have been used at lot of places in your file. So its better to import all required methods, functions from module and use them. You can import many functions from same library in one liner.
The way I've solved this in the past is to have an __init__.py file in each folder where the sources exist, then all your imports can go in there
There are even better ways of organizing python files. For more information on how to organize modules, see the official documentation
docs.python.org
stackoverflow
Also checkout importanize
Agree that from Tkinter import * is best avoided.
One way I found to deal with long imports on any given module. Not totally clean, but less wordy than the 1 per line repeats you have.
I would have done it with your TKinter import list, but I don't have it installed, so using sys instead.
#opening a parenthesis allows for implicit line feeds
from sys import (
stderr, stdout, stdin, #could have more...
#dont need this anymore
# maxint,
#maxsize, #dont this need anymore either
argv,
)
print globals().keys()
output:
['stdout', '__builtins__', '__file__', 'stdin', 'argv', '__package__', 'stderr', '__name__', '__doc__']

Why don't I have Tkinter? [duplicate]

This question already has answers here:
ImportError: No module named 'Tkinter'
(27 answers)
Closed 6 years ago.
I'm trying to test GUI code using Python 3.2 with standard library Tkinter but I can't import the library.
This is my test code:
from Tkinter import *
root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
root.mainloop()
The shell reports this error:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
from Tkinter import *
ImportError: No module named Tkinter
The root of the problem is that the Tkinter module is named Tkinter (capital "T") in python 2.x, and tkinter (lowercase "t") in python 3.x.
To make your code work in both Python 2 and 3 you can do something like this:
try:
# for Python2
from Tkinter import *
except ImportError:
# for Python3
from tkinter import *
However, PEP8 has this to say about wildcard imports:
Wildcard imports ( from <module> import * ) should be avoided
In spite of countless tutorials that ignore PEP8, the PEP8-compliant way to import would be something like this:
import tkinter as tk
When importing in this way, you need to prefix all tkinter commands with tk. (eg: root = tk.Tk(), etc). This will make your code easier to understand at the expense of a tiny bit more typing. Given that both tkinter and ttk are often used together and import classes with the same name, this is a Good Thing. As the Zen of python states: "explicit is better than implicit".
Note: The as tk part is optional, but lets you do a little less typing: tk.Button(...) vs tkinter.Button(...)
The module is called tkinter, not Tkinter, in 3.x.
Rewrite the code as follows with Tkinter as tkinter (lowercase) for 3.x:
from tkinter import *
root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
root.mainloop()

Import * statement in Python

I thought that
from tkinter import *
imports all names into my current file's namespace so that I can access all of it directly. However, I get an error on instantiating a message box:
messagebox.showinfo("Something")
Once I add
from tkinter import messagebox
all works fine. I don't understand why. Didn't the first import statement already import all names in the tkinter module including messagebox?
Importing a module (tkinter) does not automatically import submodules (tkinter.messagebox) unless the module do it explicitly for you.
messagebox is a submodule of tkinter.
You should import module "messagebox"
(use "import ... as ..." to make it shorter)
import tkinter.messagebox
tkinter.messagebox.showinfo("Something")
Or as you figured out yourself,
from tkinter import messagebox
Since messagebox is a file inside the Tkinter module, you won't be able to access it by just calling Tkinter. To import the submodules you have to call out the specific files like this:
from tkinter import messagebox

Categories

Resources