本文目录一览:
- 1、python的spyder怎么打开,或者具体的安装教程
- 2、如何在苹果系统上安装PyQt4
- 3、pyqt qwiget怎样启动另一个窗体
- 4、pyqt5按钮打开文件
- 5、PyQt5安装目录中找不到designer.exe与pyrcc5.exe
python的spyder怎么打开,或者具体的安装教程
1、安装spyder
打开
下载里面最新的源码zip包,在本地解压后,cmd里cd到解压的目录下
python setup.py install
很简单的安装,安装过程中也没报什么错误。
安装后,在python安装目录下的Scripts下面会有一个spyder.bat,运行它就可以启动Spyder
如果你的系统变量里包含了这个Scripts目录,那么你在cmd中输入spyder也可以启动。
(我的系统变量Path是这样设置的: ;%PYTHON_HOME%;%PYTHON_HOME%\Scripts )
2、安装PyQt4
由于Spyder是基于PyQt4的,所以如果你启动Spyder报错误:
就安装个PyQt4 4.6+版本就可以
在windows上安装PyQt4,为了简单安装,还是直接安装whl格式的安装包,这种包是经过编译的,安装速度比较快。
(如果你之前没安装过wheel模块,你只需要
pip install wheel
)
打开
下载里面相对应python版本、系统版本的whl文件
这里我下载了个PyQt4-4.11.4-cp27-none-win32.whl
cmd里cd到该whl文件目录下
pip install PyQt4-4.11.4-cp27-none-win32.whl
安装后,你在python里面输入
import PyQt4
没报错就说明安装成功
3、一些小问题
老实说,这窗体的panel拖曳不是很方便,如果拖动得窗体都乱了样,只需要在“View”→"Reset Window Layout"即可。
----
如果在运行py文件的时候报警告:
里面说没控制台被选择,这时候你得在"View"→"Panes"→"Console"观看下,看看是有什么问题。
另外也可以在"Run"→"Configure"里,设置"Execute in a new dedicated Python console",这时候再运行py文件试试下。
如何在苹果系统上安装PyQt4
安装PtQt4前你需准备:
Xcode (10.6.1 自带Xcode)
Qt
SIP
PyQt4
创建了一个pyqt文件夹在硬盘根目录下,并将sip-4.12.1.tar.gz和PyQt-mac-gpl-snapshot-4.8.4.tar.gz放到其中并解压。
1、先安装qt,默认安装,这一步大部分人不会有问题,跳过。
2、接下来,打开终端(Terminal,在 Applications(应用程序)/Utilities(实用工具)/ 下),在终端输入:export VERSIONER_PYTHON_PREFER_32_BIT=yes。-pyqt打开文件目录
3、使用"cd 路径"命令将当前目录设为sip-4.12.1,如: cd /pyqt/sip-4.12.1/, 然后进行配置(configure)【Re-build SIP in 32bit 】在终端中执行-pyqt打开文件目录
python configure.py --arch i386
配置(configure)完成后就开始编译,在终端中执行引用make clean(清除以前的安装信息)make
编译完成后就安装,在终端中执行引用sudo make install
在这个过程中没出现错误就是安装成功了
编译安装PyQt4,过程和上面的一样。 【Build PyQt4 in 32bit 】
在终端中使用"cd 路径"命令将当前目录设为PyQt-mac-gpl-snapshot-4.8.4,如
引用cd /Users/schi/pyqt/PyQt-mac-gpl-snapshot-4.8.4
然后进行配置(configure),在终端中执行引用python configure.py --use-arch i386
配置时会遇到引用Determining the layout of your Qt installation...
This is the GPL version of PyQt 4.6 (licensed under the GNU General Public
License) for Python 2.6.2 on darwin.
Type '2' to view the GPL v2 license.
Type '3' to view the GPL v3 license.
Type 'yes' to accept the terms of the license.
Type 'no' to decline the terms of the license.
Do you accept the terms of the license?
输入yes,再按回车就行
配置(configure)完成后就开始编译,在终端中执行
引用make cleanmake
编译比较花时间,请耐心等待。
编译完成后就安装,在终端中执行
引用sudo make install
在这个过程中没出现错误就是安装成功了
也可以在IDLE中导入PyQt4的模块,能成功导入就说明安装成功
Python代码
from PyQt4 import QtCore, QtGui
下面分析一下安装过程中可能遇到的问题:
1.问题如下
##############
ld: warning: in /Library/Frameworks/Python.framework/Python, missing required architecture x86_64 in file-pyqt打开文件目录
Undefined symbols:
"_Py_Initialize", referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
"_PyLong_AsVoidPtr", referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
"_PyErr_Print", referenced from:
PyCustomWidgets::getModuleAttr(char const*, char const*)in pluginloader.o
PyCustomWidgets::getModuleAttr(char const*, char const*)in pluginloader.o
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
"_PyString_FromString", referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
"_PyType_IsSubtype", referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
"_PyModule_GetDict", referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
"_PyObject_CallObject", referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
"_PyObject_CallFunctionObjArgs", referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
"_PyList_Append", referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
"_Py_IsInitialized", referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
"_PyDict_Next", referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
"_PyImport_ImportModule", referenced from:
PyCustomWidgets::getModuleAttr(char const*, char const*)in pluginloader.o
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
"_PyObject_GetAttrString", referenced from:
PyCustomWidgets::getModuleAttr(char const*, char const*)in pluginloader.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make[1]: *** [libpythonplugin.dylib] Error 1
make: *** [all] Error 2
这个问题的原因就是:qt是在32位mac上编译的,但pyqt默认是在64位机子上编译的,所以我们在编译的时候要制定编译环境:是i386 还是x86_64.
请参考如下的信息:
The problem is that the Qt library is 32bit while, by default, python builds PyQt4 in 64bit. That caused problem when it tried to link 64bit object files with 32bit Qt library. To fix this issue, we need to force python to build PyQt4 in 32bit, and we also need to re-build SIP in 32bit mode. If you use the python version that comes with Mac OS (2.5 for Snow Leopard), make sure that it runs in 32bit mode by issuing the command-pyqt打开文件目录
2.个问题如下:
from PyQt4 import QtGui
Traceback (most recent call last):
File "stdin", line 1, in module
ImportError: dlopen(/Library/Python/2.6/site-packages/PyQt4/QtGui.so, 2): Symbol not found: __ZN13QPyTextObject16staticMetaObjectE-pyqt打开文件目录
Referenced from: /Library/Python/2.6/site-packages/PyQt4/QtGui.so
Expected in: flat namespace
in /Library/Python/2.6/site-packages/PyQt4/QtGui.so
这个问题是所有的包安装都没有问题但是当导入QtGui或其他包时,总报这个问题,这个问题的原因是,当前pyqt release的包本身带的一个bug,PyQt-mac-gpl-snapshot-4.8.3, 所以你下载下个要release的包就可以了。如我下的是:PyQt-mac-gpl-snapshot-4.8.4。-pyqt打开文件目录
下面给大家介绍一下我写的自动安装这些程序的python源码:
#!/usr/bin/env python
"""
Automated installer for Python 2.6 (final)
This installer is able to handle any previous
versions of Python.
NOTE: This file *must* be copied to
//nssgsvr/tools/pyInstall_OSX when modified!
"""
import os
import sys
import re
import shutil
import platform
import tarfile
# Constants
PYTHON_PKGS = {"dmgFile" : "python-2.6.1-macosx2008-12-06.dmg",
"mpkgList": ["MacPython.mpkg"] }
#WXPYTHON_PKGS = {"dmgFile" : "wxPython2.8-osx-unicode-2.8.9.2-universal-py2.6.dmg",
# "mpkgList": ["wxPython2.8-osx-unicode-universal-py2.6.pkg"] }
#ANGELIA
XCODE_PKGS = {"dmgFile" : None, "mpkgList": ["Xcode.mpkg"]}
QT_PKGS = {"dmgFile" : "qt-mac-cocoa-opensource-4.6.2.dmg",
"mpkgList": ["Qt.mpkg"] }
THIRD_PARTY_INSTALL = ["sip-4.12.1", "PyQt-mac-gpl-snapshot-4.8.4","Pyro-3.9.1", "pyserial-2.4"]
# Environment constants
TCSH_ENV_FILE = '/etc/csh.login'
BASH_ENV_FILE = '/etc/profile'
SCRIPTS_ROOT_ENV = "TEST_SCRIPTS_ROOT"
TARGET_VER = "2.6"
IS_POSIX = (os.name == 'posix')
IS_MAC = (sys.version.find('Apple') != -1)
IS_OSX = (IS_MAC and IS_POSIX)
IS_OSX_LEOPARD = (IS_OSX and platform.mac_ver()[0].startswith('10.5'))
IS_OSX_SNOWLEOPARD = (IS_OSX and platform.mac_ver()[0].startswith('10.6'))
# NSSGSVR Constants
MOUNT_POINT = "/Volumes/Test"
HOSTSERVER = "NSSGSVR.global.avidww.com" # Server that contains SQA scripts
SHARE = "TEST" # NSSGSVR share that contains the Python scripts directory
USER = "qatest"
PASSWD = "Cmqat/$/$/$" # slashes needed to escape special character '$'
##################################################################################
class InstallerError(Exception):
""" Installer Exception class """
def __init__(self, description):
self.desc = description
def __str__(self):
return self.desc
class PkgInstaller:
""" Installer class for pkg files."""
def __init__(self, packageName, mpkgList, dmgFile = None ):
"""
packageName (str) Name of "package" to be installed
dmgFile (str) Path to dmg file to mount
mpkgList (list) List of mpkg files to launch when dmg file is mounted
"""
self.dmgFile = dmgFile
self.packageName = packageName
self.mpkgList = mpkgList
self.mountpoint = os.path.join(os.getcwd(), self.packageName)
self.removeMountPoint = False
if not type(self.mpkgList) == list:
raise InstallerError("Expected list for parameter mpkgList received %s" % /
type(self.mpkgList))
# Mountroot must exist for hdiutil to succeed.
if not os.path.exists(self.mountpoint):
print "Creating mountroot %s" % (self.mountpoint)
os.makedirs(self.mountpoint)
self.removeMountPoint = True
def _cleanup(self):
"""
## Performs cleanup
"""
unmount_cmd = "hdiutil unmount %s" % (self.mountpoint)
if self.dmgFile:
print "Unmounting %s" % (self.mountpoint)
ret = os.system(unmount_cmd)
if ret:
raise InstallerError("hdiutil unmount of %s failed: errno %d" % /
(self.mountpoint, ret))
if self.removeMountPoint:
print "Removing directory %s" % (self.mountpoint)
os.rmdir(self.mountpoint)
def _mount_dmg(self):
""" Mounts the dmg file. """
hdiutil_mount = "hdiutil mount %s -mountpoint %s" % (self.dmgFile,
self.mountpoint)
if os.path.exists(self.dmgFile):
print "Mounting %s" % (self.dmgFile)
ret = os.system(hdiutil_mount)
if ret:
raise InstallerError("hdiutil mount of %s failed: errno %d" % (self.dmgFile, ret))
else:
raise InstallerError("DMG file %s does not exist" % (self.dmgFile))
def _launch_pkgs(self):
""" Launches the pkg installers. """
for install_file in self.mpkgList:
if install_file.endswith('pkg'):
install_path = os.path.join(self.mountpoint, install_file)
if not os.path.exists(install_path):
raise InstallerError("File %s does not exist" % (install_path))
# 'installer' is Apple's package installer tool.
# -pkg specifies the package to be installed
# -target specifies the destination install volume
# -allow allows the installer to automatically upgrade any previous packages
# see 'man installer' for more details.
cmd = 'installer -pkg "%s" -target / -verbose -allow' % (install_path)
ret = os.system(cmd)
if ret:
msg = "Package %s failed to install: err %d" % (install_file, ret)
raise InstallerError(msg)
else:
raise InstallerError("File %s is not a valid package file" % install_file)
def install(self):
""" Main installer method. """
print "Installing package %s" % (self.packageName)
if self.dmgFile:
self._mount_dmg()
self._launch_pkgs()
self._cleanup()
print "Finished installing package %s" % (self.packageName)
def set_all_test_scripts_root(path):
"""
## Sets TEST_SCRIPTS_ROOT to path for
## both Bash and Tcsh shells if needed.
"""
bash_line = 'export TEST_SCRIPTS_ROOT="%s"' % (path)
tcsh_line = 'setenv TEST_SCRIPTS_ROOT "%s"' % (path)
pyqt qwiget怎样启动另一个窗体
一、Pyqt5
创建第一个窗体
很多人写窗体程序都是直接敲代码,不使用设计器,我个人不是很赞成这种做法。使用设计器的好处是直观、维护方便,尤其开发复杂窗体的效率高。
但是每次修改ui文件后,需要重新生成py文件,会将原来的内容覆盖掉,为了避免这种情况,引入了一个中间类。主要步骤如下:
1使用QtDesigner创建一个简单的对话框,保存成simpleDialog.ui。
2使用cmd,进入simpleDialog.ui文件所在的目录,运行命令pyuic5
simpleDialog.ui
ui_simpleDialog.py
3打开ui_simpleDialog.py,pyqt自动生成的代码如下(无需任何修改):
from
PyQt5
import
QtCore,
QtGui,
QtWidgets
class
Ui_Form(object):#注意pyqt5窗体从object继承,不是QMainWindow了
def
setupUi(self,
Form):
Form.setObjectName("Form")
Form.resize(400,
300)
self.pushButton
=
QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(60,
70,
241,
131))
self.pushButton.setObjectName("pushButton")
self.retranslateUi(Form)
self.pushButton.clicked.connect(Form.close)
QtCore.QMetaObject.connectSlotsByName(Form)
def
retranslateUi(self,
Form):
_translate
=
QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form",
"Form"))
self.pushButton.setText(_translate("Form",
"PushButton"))
可以看到刚才新建的对话框的类名称是”Ui_Form”。
4新建一个simpleDialog.py文件,编写代码如下:
from
PyQt5
import
QtCore,
QtGui,
QtWidgets
from
ui_simpledialog
import
Ui_Form
import
sys
class
SimpleDialogForm(Ui_Form):#从自动生成的界面类继承
def
__init__(self,
parent
=
None):
super(SimpleDialogForm,
self).__init__()
def
yourFunctions(self):
Pass
#这个类中处理你自己的业务逻辑。界面ui可随心所欲的修改,不影响你已经编写的逻辑。
自定义一个类(SimpleDialogForm)继承自pyqt自动生成的类,然后覆写”构造函数”,剩余的工作就是你自己想要添加的功能了。
5完善运行测试代码,如下:
if
__name__
==
"__main__":
app
=
QtWidgets.QApplication(sys.argv)
main
=
QtWidgets.QMainWindow()#创建一个主窗体(必须要有一个主窗体)
content
=
SimpleDialogForm()#创建对话框
content.setupUi(main)#将对话框依附于主窗体
main.show()#主窗体显示
sys.exit(app.exec_())
6为什么要这么做?
基于界面与实现分离的原则,我们使用QtDesigner设计的窗体,仅仅作为界面使用,具体业务逻辑通过单独的文件实现,这样以后如果界面发生变动,pyqt自动生成窗体代码时不会覆盖掉我们已经编写的业务逻辑。-pyqt打开文件目录
7推荐的做法:
为了有良好的封装性,将中间类修改为:
class
SimpleDialogForm(Ui_Form,
QtWidgets.QMainWindow):
def
__init__(self,
parent
=
None):
super(SimpleDialogForm,
self).__init__()
self.setupUi(self)#在此设置界面
#在此,可添加自定义的信号绑定
self.pushButton.clicked.connect(self.openFile)
self.pushButton_2.clicked.connect(self.closeApp)
测试代码这样写:
if
__name__
==
"__main__":
app
=
QtWidgets.QApplication(sys.argv)
main
=
SimpleDialogForm()
main.show()#在外面只需要调用simpleDialogForm显示就行,不需要关注内部如何实现了。
sys.exit(app.exec_())
pyqt5按钮打开文件
[python] view plain copy
import sys
import os
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class Notepad(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
openAction = QAction('Open', self)
openAction.setShortcut('Ctrl+O')
openAction.setStatusTip('Open a file')
openAction.triggered.connect(self.openFile)
closeAction = QAction('Close', self)
closeAction.setShortcut('Ctrl+Q')
closeAction.setStatusTip('Close Notepad')
closeAction.triggered.connect(self.close)
menubar = self.menuBar()
fileMenu = menubar.addMenu('File')
fileMenu.addAction(openAction)
fileMenu.addAction(closeAction)
self.textEdit = QTextEdit(self)
self.textEdit.setFocus()
self.textEdit.setReadOnly(True)
self.resize(700, 800)
self.setWindowTitle('Notepad')
self.setCentralWidget(self.textEdit)
self.show()
def openFile(self):
filename, _ = QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME'))
fh = ''
if QFile.exists(filename):
fh = QFile(filename)
if not fh.open(QFile.ReadOnly):
QtGui.qApp.quit()
data = fh.readAll()
codec = QTextCodec.codecForUtfText(data)
unistr = codec.toUnicode(data)
tmp = ('Notepad: %s' % filename)
self.setWindowTitle(tmp)
self.textEdit.setText(unistr)
def main():
app = QApplication(sys.argv)
notepad = Notepad()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
PyQt5安装目录中找不到designer.exe与pyrcc5.exe
PyQt5不再提供Qt Designer等工具,所以需要再安装pyqt5-tools
打开cmd执行:
pip install pyqt5-tools
pyrcc5.exe文件,我是在在这个目录下找到的.../Python/Python36/Scripts/pyrcc5.exe,就是你安装python目录中的scripts文件夹中