모듈 가져 오기 예외를 처리하는 방법을 어디에서나 솔루션을 찾을 수 없습니다. '마법 부여'모듈을 가져와야하지만 먼저 설치되었는지 확인해야합니다. 설치되지 않았다면 오류 메시지를 표시해야합니다. 그래서 내가 이렇게하면 QMessageBox를 보여줄 방법이 없습니다. 메인 클래스가 아직 생성되지 않았기 때문입니다.PyQt - 모듈 가져 오기 예외를 처리하는 방법
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)
내가 할 경우이 :
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)
다음 인터프리터는 불평 "나가서 설명하자면 NameError : 전역 이름 '인챈트'가 정의되어 있지 않습니다."
모듈 가져 오기 예외 메시지를 표시하는 방법 또는 전체 프로그램에서 모듈을 작동시키는 방법을 알려주십시오. 고맙습니다. 사용자로, 맞춤법 검사는 옵션 기능이있는 경우,
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)
그러나 :
이__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())
해당 모듈없이 앱을 실행할 수 있습니까? 그렇지 않다면, 정규 예외로 스크립트를 종료하게하십시오. – Avaris