为什么命名/通配符导入会/如何影响参数? [英] Why/how does named vs wildcard import affect parameters?

查看:108
本文介绍了为什么命名/通配符导入会/如何影响参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以...我正在修改一些基本的python/tkinter程序,并将正在阅读的书中python 2.x的代码翻译为3.x,以确保我理解所有内容.我还尝试用名为"proper"的导入而不是通配符导入来编写代码,即from tkinter import *,但效果不佳...

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

此刻我感到困惑的是:原始代码对tkinter进行了通配符导入,并且似乎可以不使用诸如sticky=W之类的参数变量引号来逃避"名为import的导入,我必须在'W'周围使用引号,否则会出现错误Unresolved reference 'W'.

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)

root.mainloop()

命名导入:

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

两者都能工作,但是python为什么一次只能识别一种方式,而另一次却不能呢?

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

推荐答案

from tkinter import *

tkinter模块加载所有内容,并将其放入全局名称空间中.

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

import tkinter as tk

tkinter模块的加载所有内容,并将它们全部放在tk命名空间中.所以Label现在是tk.Label,而Wtk.W

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

您的第三个选项是:

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.

幸运的是,您只有一个import *,否则您将很难确定所有内容均来自哪个模块!

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'

它们只是常量.您可以传递字符串 value ,它也可以正常工作.

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

这篇关于为什么命名/通配符导入会/如何影响参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆