Why/how does named vs wildcard import affect parameters?

So... I'm tinkering with some basic python/tkinter programs, and translating the code from python 2.x in the book I'm reading, to 3.x to make sure I understand everything. I was also attempting to write the code with 'proper' named imports instead of wild card import i.e. from tkinter import * but its not working out so well...

What has me baffled at the moment is this: the original code does a wildcard import of tkinter, and seems to be able to 'get away with' not using quotes around parameter variables like sticky=W, while if I do a named import I have to use quotes around the 'W' or I get an error Unresolved reference 'W'.

Example code (wildcard import):

from tkinter import *
root = Tk()

Label(root, text="Username").grid(row=0, sticky=W)
Label(root, text="Password").grid(row=1, sticky=W)
Entry(root).grid(row=0, column=1, sticky=E)
Entry(root).grid(row=1, column=1, sticky=E)
Button(root, text="Login").grid(row=2, column=1, sticky=E)


Named import:

import tkinter as tk

root = tk.Tk()

tk.Label(root, text="Username").grid(row=0, sticky='W')
tk.Label(root, text="Password").grid(row=1, sticky='W')
tk.Entry(root).grid(row=0, column=1, sticky='E')
tk.Entry(root).grid(row=1, column=1, sticky='E')
tk.Button(root, text="Login").grid(row=2, column=1, sticky='E')


Both work, but why does python recognize it one way one time, and not the other?


from tkinter import *

Loads everything from tkinter module, and puts it in the global namespace.

import tkinter as tk

Loads everything from tkinter module, and put it all in the tk namespace. So Label is now tk.Label, and W is tk.W

Your third option, which is better when you only need a few objects from the module, would be:

from tkinter import Label, Entry, Button, W, E, Tk

Etc. Again, better when you just need one or two. Not good for your situation. Just included for completeness.

Fortunately you only have one import * or you'd have a much harder time determining which module everything came from!

tkinter.W = 'w'
tkinter.E = 'e'
tkinter.S = 's'
tkinter.N = 'n'

They're just constants. You could pass the string value and it would work just as well.

Need Your Help

PDO insert array

php mysql arrays pdo

Reccently I have been attempting to insert an array into a database, I keep getting the error message "Notice: Array to string conversion", I not really sure how to resolve this issue, any advice w...

formatting using table print gem using Ruby

ruby json date-formatting

The output of my Json file is hash. I'm iterating over each line and using the tp gem to format it. My question is how do I format the width so that all my data is displayed neatly in the terminal....