【发布时间】:2023-03-24 20:05:01
【问题描述】:
我正在通过 Anaconda 运行 Python 2.7,据我所知没有安装 Python 3。我对导入tkinter 感到困惑。 Stack Overflow 上的其他几个问题表明,tkinter 有单独的模块和略有不同的导入语法,具体取决于您运行的是 Python 2 还是 Python 3。但是,Python 3 语法 有点 有效在 Python 2 中对我来说(参见下面代码中的 cmets)。什么给了?
import sys
print sys.version
# prints: 2.7.12 |Continuum Analytics, Inc.| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)]
# I hear these should not work in Python 2.
# In reality, they work fine if run normally via the Python 2 interpreter.
# However, they do NOT work when I use pyinstaller to make an executable.
from tkinter import *
from tkinter import ttk, messagebox
# These work fine in Python 2, as they should, even if compiled into an exe.
from Tkinter import *
import ttk
import tkMessageBox
编辑:
针对 Bryan Oakley 的评论,print sys.path 的结果是:
['C:\\Users\\...\\tkinter test program',
'C:\\Miniconda\\python27.zip',
'C:\\Miniconda\\DLLs',
'C:\\Miniconda\\lib',
'C:\\Miniconda\\lib\\plat-win',
'C:\\Miniconda\\lib\\lib-tk',
'C:\\Miniconda',
'C:\\Miniconda\\lib\\site-packages',
'C:\\Miniconda\\lib\\site-packages\\win32',
'C:\\Miniconda\\lib\\site-packages\\win32\\lib',
'C:\\Miniconda\\lib\\site-packages\\Pythonwin',
'C:\\Miniconda\\lib\\site-packages\\setuptools-23.0.0-py2.7.egg']
针对 Sun Bear 的回答,我的电脑上发生了以下情况:
C:\>python
Python 2.7.12 |Continuum Analytics, Inc.| (default, Jun 29 2016, 11:07:13) [MSC
v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
>>> import tkinter
>>>
回应 Łukasz Rogalski 的评论:
>>> import Tkinter
>>> print Tkinter.__file__
C:\Miniconda\lib\lib-tk\Tkinter.pyc
>>> import tkinter
>>> print tkinter.__file__
C:\Miniconda\lib\site-packages\tkinter\__init__.pyc
>>>
针对 Sun Bear 回答的 cmets 中的讨论,这是 C:\Miniconda\lib\site-packages\tkinter\__init__.pyc 的内容,这解释了为什么即使我使用的是 Python 2,import tkinter 也能工作:
from __future__ import absolute_import
import sys
if sys.version_info[0] < 3:
from Tkinter import *
else:
raise ImportError('This package should not be accessible on Python 3. '
'Either you are trying to run from the python-future src folder '
'or your installation of python-future is corrupted.')
【问题讨论】:
-
在 macOS 上不适合我(“ImportError: No module named tkinter”)。
-
Windows 上不区分大小写的文件系统,也许吧?但是一个区分大小写的 .zip 存档,当捆绑到可执行文件中时......
-
我不认为这是不区分大小写的问题,因为
ttk和messagebox仅在tkinter中,而不是Tkinter。这失败了:from Tkinter import ttk -
通过任何更改,您在工作目录中有一个名为
tkinter.py的文件? -
打印出
sys.path。很可能,您的路径中有 python 3 库的位置。
标签: python tkinter python-2.x pyinstaller