简体   繁体   English

为什么命名/通配符导入会/如何影响参数?

[英]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. 所以...我正在修补一些基本的python / tkinter程序,并将正在阅读的书中的python 2.x的代码翻译为3.x,以确保我理解所有内容。 I was also attempting to write the code with 'proper' named imports instead of wild card import ie from tkinter import * but its not working out so well... 我还试图用名为“ proper”的导入而不是通配符导入(即from tkinter import *编写代码,但效果不佳...

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' . 目前让我感到困惑的是:原始代码对tkinter进行了通配符导入,并且似乎能够不使用诸如sticky=W类的参数变量加引号而“逃脱”,而如果我执行命名导入,必须在'W'周围使用引号,否则会出现错误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 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')

root.mainloop()

Both work, but why does python recognize it one way one time, and not the other? 两者都起作用,但是为什么python一次只能识别一种方式,而另一次却不能呢?

from tkinter import *

Loads everything from tkinter module, and puts it in the global namespace. tkinter模块加载所有内容,并将其放入全局名称空间中。


import tkinter as tk

Loads everything from tkinter module, and put it all in the tk namespace. tkinter模块加载所有内容, 并将其全部放入tk命名空间中。 So Label is now tk.Label , and W is tk.W 所以Label现在是tk.LabelWtk.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! 幸运的是,您只有一个import *否则您将很难确定所有内容来自哪个模块!


Edit: 编辑:

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. 您可以传递字符串 ,它也可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM