Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

python - Tkinter importing without *?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...