python - Why/how does named vs wildcard import affect parameters? -
so... i'm tinkering basic python/tkinter programs, , translating code python 2.x in book i'm reading, 3.x make sure understand everything. attempting write code 'proper' named imports instead of wild card import i.e. from tkinter import * not working out well...
what has me baffled @ moment this: original code wildcard import of tkinter, , seems able 'get away with' not using quotes around parameter variables sticky=w, while if named import have use quotes around 'w' or 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) root.mainloop() named import:
import tkinter 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') root.mainloop() both work, why python recognize 1 way 1 time, , not other?
from tkinter import * loads tkinter module, , puts in global namespace.
import tkinter tk loads tkinter module, and put in tk namespace. label tk.label, , w tk.w
your third option, better when need few objects module, be:
from tkinter import label, entry, button, w, e, tk etc. again, better when need 1 or two. not situation. included completeness.
fortunately have 1 import * or you'd have harder time determining module came from!
edit:
tkinter.w = 'w' tkinter.e = 'e' tkinter.s = 's' tkinter.n = 'n' they're constants. pass string value , work well.
Comments
Post a Comment