Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7018861
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T23:06:26+00:00 2026-05-27T23:06:26+00:00

I can’t find a solution anywhere how to handle module import exceptions. I need

  • 0

I can’t find a solution anywhere how to handle module import exceptions. I need to import ‘enchant’ module but I have to check if it’s installed first. And I need to show an error message if it’s not installed. So if I do this, there’s no way to show the QMessageBox because the main class hasn’t been created yet.

import sys
import re

from PyQt4.QtCore import *
from PyQt4.QtGui import *

try:
    import enchant
    dict_list = enchant.list_languages()
    if "ru_RU" in dict_list:
        self.dict = enchant.Dict("ru_RU")
    else:
        self.dict = enchant.Dict()
except ImportError, inst:
    #How do I graphically show an error message here if the class hasn't been set up yet?

class Translit(QMainWindow):
    def __init__(self, parent = None):
        super(Translit, self).__init__(parent)

If I do this:

import sys
import re

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Translit(QMainWindow):
    def __init__(self, parent = None):
        super(Translit, self).__init__(parent)

    try:
        import enchant
        dict_list = enchant.list_languages()
        if "ru_RU" in dict_list:
            self.dict = enchant.Dict("ru_RU")
        else:
            self.dict = enchant.Dict()
    except ImportError, inst:
        QMessageBox.warning(parent, "", "Error:\n%s seems to be installed\n\nSpell checking will be disabled" % (inst))

    self.change_dict()

    def change_dict(self):
        self.dict = enchant.Dict("en_US")
        QMessageBox.about(parent,"","Spellcheck is set to " + self.dict.tag)

then the interpreter complains “NameError: global name ‘enchant’ is not defined”.

Please show me how I can show module import exception messages or how to make that module work throughout the whole program. Thank you.

Here’s an original source I’m trying to reuse:

__license__ = 'MIT'
__copyright__ = '2009, John Schember '
__docformat__ = 'restructuredtext en'

import re
import sys

import enchant

from PyQt4.Qt import QAction
from PyQt4.Qt import QApplication
from PyQt4.Qt import QEvent
from PyQt4.Qt import QMenu
from PyQt4.Qt import QMouseEvent
from PyQt4.Qt import QPlainTextEdit
from PyQt4.Qt import QSyntaxHighlighter
from PyQt4.Qt import QTextCharFormat
from PyQt4.Qt import QTextCursor
from PyQt4.Qt import Qt
from PyQt4.QtCore import pyqtSignal


class SpellTextEdit(QPlainTextEdit):

def __init__(self, *args):
    QPlainTextEdit.__init__(self, *args)

    # Default dictionary based on the current locale.
    self.dict = enchant.Dict("ru_RU")
    self.highlighter = Highlighter(self.document())
    self.highlighter.setDict(self.dict)

def mousePressEvent(self, event):
    if event.button() == Qt.RightButton:
        # Rewrite the mouse event to a left button event so the cursor is
        # moved to the location of the pointer.
        event = QMouseEvent(QEvent.MouseButtonPress, event.pos(),
            Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
    QPlainTextEdit.mousePressEvent(self, event)

def contextMenuEvent(self, event):
    popup_menu = self.createStandardContextMenu()

    # Select the word under the cursor.
    cursor = self.textCursor()
    cursor.select(QTextCursor.WordUnderCursor)
    self.setTextCursor(cursor)

    # Check if the selected word is misspelled and offer spelling
    # suggestions if it is.
    if self.textCursor().hasSelection():
        text = unicode(self.textCursor().selectedText())
        if not self.dict.check(text):
            spell_menu = QMenu('Spelling Suggestions')
            for word in self.dict.suggest(text):
                action = SpellAction(word, spell_menu)
                action.correct.connect(self.correctWord)
                spell_menu.addAction(action)
            # Only add the spelling suggests to the menu if there are
            # suggestions.
            if len(spell_menu.actions()) != 0:
                popup_menu.insertSeparator(popup_menu.actions()[0])
                popup_menu.insertMenu(popup_menu.actions()[0], spell_menu)

    popup_menu.exec_(event.globalPos())

def correctWord(self, word):
    '''
    Replaces the selected text with word.
    '''
    cursor = self.textCursor()
    cursor.beginEditBlock()

    cursor.removeSelectedText()
    cursor.insertText(word)

    cursor.endEditBlock()

class Highlighter(QSyntaxHighlighter):

WORDS = u'(?iu)[\w\']+'

def __init__(self, *args):
    QSyntaxHighlighter.__init__(self, *args)

    self.dict = None

def setDict(self, dict):
    self.dict = dict

def highlightBlock(self, text):
    if not self.dict:
        return

    text = unicode(text)

    format = QTextCharFormat()
    format.setUnderlineColor(Qt.red)
    format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)

    for word_object in re.finditer(self.WORDS, text):
        if not self.dict.check(word_object.group()):
            self.setFormat(word_object.start(),
                word_object.end() - word_object.start(), format)

class SpellAction(QAction):

'''
A special QAction that returns the text in a signal.
'''

correct = pyqtSignal(unicode)

def __init__(self, *args):
    QAction.__init__(self, *args)

    self.triggered.connect(lambda x: self.correct.emit(
        unicode(self.text())))

def main(args=sys.argv):
app = QApplication(args)

spellEdit = SpellTextEdit()
spellEdit.show()

return app.exec_()

if __name__ == '__main__':
    sys.exit(main()) 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T23:06:26+00:00Added an answer on May 27, 2026 at 11:06 pm

    Here’s one possible fix for your problem:

    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    
    try:
        import enchant
    except ImportError:
        enchant = None
    
    class Translit(QMainWindow):
        def __init__(self, parent = None):
            super(Translit, self).__init__(parent)
            if enchant is not None:
                dict_list = enchant.list_languages()
                if "ru_RU" in dict_list:
                    self.dict = enchant.Dict("ru_RU")
                else:
                    self.dict = enchant.Dict()
                self.change_dict()
            else:
                self.dict = None
                QMessageBox.warning(parent, "",
                    "Error: could not import the 'enchant' module\n\n"
                    "Spell checking will be disabled")
    
        def change_dict(self):
            if self.dict is not None:
                self.dict = enchant.Dict("en_US")
                QMessageBox.about(
                    parent, "", "Spellcheck is set to " + self.dict.tag)
    

    However, if spell checking is an optional feature, as a user I would be pretty annoyed if I got this warning message every time I ran the application.

    It would be better show the warning when the user first tries to access the spell checker (and then disable any further access). But the way to go about doing that will obviously depend on how the enchant module is used elsewhere within your application.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can anyone (maybe an XSL-fan?) help me find any advantages with handling presentation of
I have a jquery bug and I've been looking for hours now, I can't
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
Can anyone suggest how to underline the title of a UIButton ? I have
Can someone maybe tell me why this is not working? I have used echo
Can anybody tell me a regular expression to use within some PHP to find
Can I have a project that has some parts written in c and other
Can you have submenus with the top level set to checkable in WPF? I
Can anyone help me trying to find out why this doesn't work. The brushes
Can someone guide me on a possible solution? I don't want to use /bin/cp

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.