【发布时间】:2016-07-09 21:09:29
【问题描述】:
与通过 IDLE 的 run module f5 命令运行相比,通过命令行运行代码会引发错误是否有原因?
最近我一直在努力提高我的代码的可读性和健壮性。结果,我一直在尝试删除所有 from module import * 行。我曾经使用from tkinter import *,我的这行代码运行良好:
self.path = filedialog.askdirectory()
但现在我已将from tkinter import * 更改为import tkinter as tk 并相应地更改了代码:
self.path = tk.filedialog.askdirectory()
一个名为 GUI.py 的文件使用以下命令导入此文件:from lib.filesearch import *(我提到的代码行位于文件搜索文件中。)
我通过 IDLE 运行我的代码,一切都很好。我的 GUI 仍然可以工作,self.path = tk.filedialog.askdirectory() 行正常工作但是,当我通过 windows 命令行运行代码时,我得到了错误:
AttributeError: 'module' object has no attribute 'filedialog'
以下是我的代码中的相关位:
来自文件搜索.py
import tkinter as tk
def get_path(self):
"""Store user chosen path to search"""
self.paths = tk.filedialog.askdirectory(initialdir = FileSearch.DEFAULT)
return self.paths
来自 GUI.py
from lib.filesearch import *
def Browse(self):
self.BrowseB['state']='disabled'
self.p=self.CrawlObj.get_path()
self.AddText('Searching from Path: ' + str(self.p))
self.BrowseB['state']='normal'
与question 不同,我只安装了一个版本的 python。即 Python34。
【问题讨论】:
-
尝试添加一个简单的调试
print(tk)以查看它实际导入的内容。最初会想到不同的 python 路径。 -
@Ilja 来自 IDLE:
<module 'tkinter' from 'C:\\Python34\\lib\\tkinter\\__init__.py'>和来自命令行:<module 'tkinter' from 'C:\\Python34\\lib\\tkinter\\__init__.py'> -
你需要导入带有
import tkinter.filedialog的子模块来加载它,你没有在IDLE中的原因是因为idle已经导入了它,因为它在tkinter上运行 -
看看the docs关于在他们的
__init__.py中定义__all__属性的包,它定义了在导入顶级模块时要加载哪些子模块,一些包像numpy或matplotlib导入 lots 个子模块,这就是为什么它们需要很长时间才能加载,但其他包(如tkinter和PIL)只会加载您明确要求它们加载的包。 -
这在某种意义上是IDLE中的一个bug,它的内部操作以这种方式暴露出来。我希望有一天通过重构几个模块来解决这个问题,这样在用户代码运行之前甚至不会将 tkinter 导入用户进程。
标签: python python-3.x import tkinter namespaces