我通過Anaconda運行Python 2.7,並且沒有安裝Python 3,據我所知。我對輸入tkinter
感到困惑。關於Stack Overflow的其他幾個問題表明tkinter
中有單獨的模塊和略有不同的導入語法,具體取決於您是運行Python 2還是Python 3.然而,Python 3語法種類適用於Python 2中的我(請參閱以下代碼評論)。是什麼賦予了?爲什麼Python 3的tkinter導入語法似乎在Python 2中起作用?
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
編輯:
針對布萊恩奧克利的評論中,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']
針對馬來熊的答案,這裏是我的電腦上會發生什麼:
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
>>>
In res ponse到盧卡斯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
>>>
爲應對馬來熊的答案的意見的討論,這是C:\Miniconda\lib\site-packages\tkinter\__init__.pyc
的內容,這可以解釋爲什麼import tkinter
工作即使我使用Python 2:
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」)。 – kennytm
Windows上的非區分大小寫文件系統,或許?但是,當綁定到可執行文件時區分大小寫的.zip存檔... – jasonharper
我不認爲這是一個不區分大小寫的問題,因爲'ttk'和'messagebox'只在'tkinter'中,而不在'Tkinter'中。這個失敗:'從Tkinter導入ttk' – MarredCheese