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
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