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()
Related
I have a Python script which generates a GUI window with tkinter library. I'd like to make some of it's buttons display a prompt - small window to ask the user for some number (something like in JavaScript). I tried the following command:
x = tkinter.simpledialog.askstring
But it returns an error:
NameError: name 'tkinter' is not defined
and no prompt is generated, although I have imported the library in the script's beginning:
from tkinter import *
from tkinter import simpledialog
Other elements (buttons, labels etc.) in the main window work correctly. Please help.
askstring is part of tkinter.simpledialog so you might import it like so
from tkinter.simpledialog import askstring
usage example
import tkinter as tk
from tkinter.simpledialog import askstring
root = tk.Tk()
x = askstring("Title", "Prompt")
print(x)
root.mainloop()
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()
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.
I want to create a tkinter window using pycharm:
from tkinter import *
root = Tk()
root.mainloop()
Apparently PyCharm tells me that from tkinter import * is an unused import statement, and root = Tk() is an unresolved reference. What's confusing me is that the code works completely fine, a tkinter window shows up, no errors.
How do I fix this?
Edit: PyCharm shows these error whenever I import any other library I have.
from Tkinter import *
root = Tk()
thislabel = Label(root, text = "This is an string.")
thislabel.pack()
root.mainloop()
Use Tkinter not tkinter
from tkinter import*
works just fine. You just have to go to the next line and type something along the lines of
tk = Tk()
or any tkinter code and it will recognize it and work just fine.
from tkinter import*
tk = Tk()
btn = Button(tk, text="Click Me")
btn.pack()
tk.mainloop()
Does that code above work?
Hope this helps
At my case, the file that I was writing had the name "tkinter.py", when I imported the module "tkinter" what PyCharm did was import the file that I was writing, of course the message error: "Cannot find reference Tk in imported module tkinter" appeared. Its a dumb error, but check that you file not called same as module. ;)
EDIT:
If you use "from tkinter import * " you must run it like this:
from tkinter import *
root = Tk()
root.mainloop()
Note the uppercase "T" in "Tk".
If you use "import tkinter as tk" you must run it like this:
import tkinter as tk
root = tk.Tk()
root.mainloop()
Note the "tk" module (lowercase) before "Tk" (uppercase).
maybe check if you installed python in a virtual environment, if so you need to work your project there too
In the end I managed to fix this problem myself, here's what I did:
Deleted the ".idea" file associated with the project.
In PyCharm: File >> Open >> "path to project" >> Ok (reopen project)
Now it it looks as normal as it was before.
I could solve it by doing the following
Delete the .idea file.
Delete the __py_cache__ file.
in python2 it is
from Tkinter import *
and is python 3 it is
from tkinter import *
I hope this helps somehow.
I have found out!!
You are actually have to install tkintertoy to use tkinter in pycharm.
In my past programming i used the following code:
from tkinter import *
Gui = Tk()
but someone told me that importing * was not good for many reasons but now when i want to import
from tkinter import geometry
it says geometry not a module thing (name).
and when i do:
import tkinter
tkinter.geometry(500x500)
it says 'module' object has no attribute 'geometry'
Can someone explain me how to import with tkinter all the different ways?? Not only for geometry but most of the tkinter modules...???
That's because the module tkinter doesn't have a geometry function. It's the Tk instances that do.
Here's a good way to accomplish what you're trying to do:
import tkinter as tk # tk is a convenient, easy to type alias to use for tkinter.
gui = tk.Tk()
gui.geometry("500x500") # don't forget the quotes
Why from tkinter import * is a non-ideal way to import tkinter
As an aside, whoever told you that from tkinter import * was a bad idea was correct - when you do that, you load all of tkinter's namespace into your module's namespace.
If you do that, you can end up with unpleasant namespace collisions, like this:
from tkinter import *
gui = Tk()
Label = "hello"
Label1 = Label(gui, text=Label)
# Traceback (most recent call last):
# File "stackoverflow.py", line 98, in <module>
# Label1 = Label(gui, text=Label)
# TypeError: 'str' object is not callable
You've overwritten the reference to tkinter's Label widget - so you can't create any more Labels! Of course you shouldn't be capitalizing local variables like that anyways, but why worry about avoiding those namespace problems when you can do this instead:
import tkinter as tk
This ^^^^ import method is also preferable because if at some point you want to swap Tkinter out for another module with a similar implementation, instead of combing through your code for all elements of the Tkinter module, you can just go like this:
#import tkinter as tk
import newTkinter as tk
And you're all set. Or, if you want to use another module that happens to have some of the same names for its classes and methods, the following would cause chaos:
from tkinter import *
from evilOverlappingModule import *
but this would be fine:
import tkinter as tk
import evilOverlappingModule as evil
The reason that from module import * is considered harmful is that it pollutes the main namespace with every public name in the module. At best this makes code less explicit, at worst, it can cause name collisions. For example, module codecs has an open method defined, and there is the built-in version, which take different arguments. If I write
from codecs import *
f = open(…)
which open will I get? Tkinter has a lot of symbols, and tkinter based programs tend to use them very heavily. better than the import * is
import tkinter as tk
which then allows the — still explicit, but easier to type and read:
tk.Tk().geometry(…)
If you * imported tkinter, essentially tkinter. is in the namespace, meaning that to access to tkinter modules without worrying about prefixing it with tkinter.. In this case, geometry("500x500") is a method of Tk(), so you would use it like this
from Tkinter import *
Gui = Tk()
Gui.geometry("500x500")
Gui.mainloop()
Similar objects, such as various widgets, etc. are used the same. For example, a label would be made like this:
from Tkinter import *
Gui = Tk()
label= Label(Gui, text="Hello World!")
label.pack()
Gui.mainloop()
I don't know why someone said that importing * wasn't good cause that isn't true, it's actually better then just importing tkinter. Importing * will make the programming easier. With just tkinter you would need to type tkinter. before doing something, or if you do it as tk, you would need to do tk., from tkinter import * is the best what you can do.
Instead of doing:
from tkinter import *
You can do:
from tkinter import Tk, Canvas #The widgets you want to use
Or:
import tkinter as tk
Here’s a quick answer: Tkinter doesn’t have a geometry function. You can use the geometry function with instances of the Tk() class.
Example:
import tkinter as tk # Use the module name ’Tkinter’ if you have Python 2
root = tk.Tk()
root.geometry(‘500x500’) # You can change the size
# Other code goes here
root.mainloop()
Just like the geometry function, the mainloop, pack, grid, place, config etc. functions are used with the instances of the class Tk()
Thank You! Hope that works!