首页 > 解决方案 > 将 UI 合并到 Python 代码中的错误

问题描述

背景:

我正在使用 python 和 PyQt5 构建这个 gui 字典应用程序。 data.json是包含键及其定义的文件(数据的排列方式类似于 python 字典)。

dictionary.ui 是我在pyqt5 设计器应用程序中构建的 UI

(小部件类=“ QMainWindow ”名称=“MainWindow”)。(小部件类=“QPushButton”名称=“ pushButton ”)。(widget class="QLineEdit" name=" lineEdit ").(widget class="QLabel" name=" resultArea ")

问题:

该程序在显示 gui 一段时间后运行。但是当我输入一些东西时,程序崩溃而没有输出。我无法修复此代码。

问题出在这行代码self.resultArea.setText(self.trasnlate(self.lineEdit.text())) 错误是Translate is a method not a class instance

我需要在lineEdit标签中输入的用户输入作为translate()方法的参数,如果单击pushButton ,则在resultArea标签中显示该方法的结果。

代码:

import json
from difflib import get_close_matches
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication,QMainWindow
from PyQt5.uic import loadUi


data = json.load(open("data.json"))

class DictionaryApp(QMainWindow) :
    def __init__(self) :
        super(DictionaryApp,self).__init__()
        loadUi('dictionary.ui',self)
        self.setWindowTitle('Dictionary')
        self.pushButton.clicked.connect(self.on_pushButton_clicked)
    @pyqtSlot()
    def on_pushButton_clicked(self) :
        self.resultArea.setText(self.trasnlate(self.lineEdit.text()))
    @staticmethod
    def translate(w) :
        w = w.lower()
        if w in data :
            return data[w]
        elif w.title() in data: 
            return data[w.title()]
        elif w.upper() in data: 
            return data[w.upper()]
        elif len(get_close_matches(w, data.keys())) > 0 :
            YN = input("Did you mean {} instead? Enter 'y' for yes, 'n' for no: ".format(get_close_matches(w, data.keys())[0])).lower()
            if YN == "y" :
                return data[get_close_matches(w, data.keys())[0]]
            elif YN == "n" :
                return "The word doesn't exist. Please double check it. "
            else :
                return "Wrong entry. "
        else :
            return "The word doesn't exist. Please double check it. "     
        
app=QApplication(sys.argv)
widget=DictionaryApp()
widget.show()
sys.exit(app.exec_())


   

标签: pythonpyqt5

解决方案


推荐阅读