Script fails with AttributeError when run in CMD, but executes fine in IDLE

眉间皱痕 提交于 2019-11-29 15:02:14

People asked about python version because tk.filedialog is spelled differently in 2.x. However, I suspect that your problem is that Idle runs code in a managed environment that masks a bug in your unposted code of not properly importing tkinter.filedialog. To illustrate, the follow is from the standard 3.4.2 console interpreter

>>> import tkinter as tk
>>> tk.filedialog
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'filedialog'

Here are the same statements in Idle's Shell.

>>> import tkinter as tk
>>> tk.filedialog
<module 'tkinter.filedialog' from 'C:\\Programs\\Python34\\lib\\tkinter\\filedialog.py'>

The reason that there is no error is because Idle has already imported the filedialog submodule as tkinter.filedialog (in sys.modules). If this is your problem also, a solution for you is to add the import below and refer to 'filedialog' without the 'tk' prefix.

>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\\Programs\\Python34\\lib\\tkinter\\filedia
log.py'>
>>> filedialog.askopenfilename
<function askopenfilename at 0x0000000000498BF8>

If this does not solve this issue, edit your question to add a truly minimal code example and explain exactly how you run both with Idle and 'CMD' (is this cmd.exe on Windows, or what?).

This looks like IDLE sets a different PYTHONPATH, or uses a different python executable; make sure you use the same version of python by checking sys.version_info from both and comparing sys.path.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!