How to solve the problem "TypeError: setEnabled(self, bool): argument 1 has unexpected type 'str'"?

Question:

I have encountered such a problem
`

> python .main.py
Traceback (most recent call last):
  File "C:main.py", line 79, in writeF
    self.ui.lineEdit.setEnabled(value)
TypeError: setEnabled(self, bool): argument 1 has unexpected type 'str'

`
My code is hosted on github, here’s the repo link.

The relevant file part:

from PyQt5 import QtWidgets, QtCore
from design import Ui_MainWindow
import sys
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #Здесь мы вносим изменения
        '''self.ui.lineEdit.setPlaceholderText("ip address1")
        self.ui.checkBox.stateChanged.connect(self.selected)
    def selected(self):
        value=True
        if self.ui.checkBox.isChecked():
            value=True
            self.ui.label_result.clear()
        else:
            value=False
            self.ui.label_result.setText("{}".format(self.ui.lineEdit.text()))
        self.ui.lineEdit.setEnabled(value)'''
        self.ui.lineEdit.setPlaceholderText("ip address1")
        self.ui.lineEdit_2.setPlaceholderText("ip address2")
        self.ui.lineEdit_3.setPlaceholderText("station name")
        self.ui.lineEdit_4.setPlaceholderText("station number")
        self.ui.lineEdit_5.setPlaceholderText("transmitter number")
        self.ui.checkBox.stateChanged.connect(self.writeF)
    def writeF(self):
    #def replData(ip1, ip2, sName, sNumb, tNumb):
        # список ключей, которые нужно будет заменить в файле template
        keys=['_ip1_', '_ip2_', '_sName_', '_sNumb_', '_tNumb_']
        #print(keys) 
        #Создаем список значений, на которые нужно будет заменить
        values=[]
        ip1 = self.ui.lineEdit.text()
        ip2 = self.ui.lineEdit_2.text()
        sName = self.ui.lineEdit_3.text()
        sNumb = self.ui.lineEdit_4.text()
        tNumb = self.ui.lineEdit_5.text()
        values.append(ip1)
        values.append(ip2)
        values.append(sName)
        values.append(sNumb)
        values.append(tNumb)
        #print(values)
        #Создаем словарь. в качестве ключей (keys) это будут список значений, в 
            #котором надо будет заменить в файле template, а в качестве значений 
            #(values) - список значений, на которые нужно будет заменить
        dictionary={}
        for i in range(len(keys)):
            dictionary[keys[i]] = values[i]
            search_text = dictionary[keys[i]]
            replace_text = keys[i]
            #print(search_text)
            #print(replace_text)
        value=True
        if self.ui.checkBox.isChecked():
            value=True
            #Считываем файл template, и меняем значения
            with open(r'template.txt', 'r') as oFile:
                rFile = oFile.read()
                for key, val in dictionary.items():
                    rFile = rFile.replace(key, str(val))
            #print(rFile) 
            #Запишем изменения в файл output
            with open(r'output.txt', 'a') as wFile:
                wFile.write('n')
                wFile.write('n')
                wFile.write('n')
                wFile.write(rFile) 
            self.ui.lineEdit.clear()
            self.ui.lineEdit_2.clear()
            self.ui.lineEdit_3.clear()
            self.ui.lineEdit_4.clear()
            self.ui.lineEdit_5.clear()
        #else:
        #    value=False
        #    self.ui.label_result.setText("{}".format(self.ui.lineEdit.text()))
        #    self.ui.label_result.setText("{}".format(ip1))
        self.ui.lineEdit.setEnabled(value)
    '''
    repeat="y"
    while repeat == "y":
        #ip1, ip2, sName, sNumb, tNumb = 1111, 2222, 3333, 4444, 5555
        #ip1, ip2, sName, sNumb, tNumb = input("Enter the IP address1: "), input("Enter the IP address2: "), input("Enter the station name: "), input("Enter the station number: "), input("Enter the transmitter number: ")    
        replData(ip1, ip2, sName, sNumb, tNumb)
        #Если нужно повторить:
        repeat = input("Do you want to continue? (y/n): ")
        if repeat == "n":
            break
        while (repeat!="y" and repeat!="n"):
            repeat = input("Please enter the correct answer (y/n): ")
    '''
app = QtWidgets.QApplication([])
application = mywindow()
application.show() 
sys.exit(app.exec())

I’m starting to learn Python. I have developed a program that reads data from the user in the GUI via pyqt5 and qt designer, writes this data to a file output.txt. But I ran into a problem that gives an error in the command line, which I showed above. What did I do wrong

Asked By: David138

||

Answers:

Short Answer: You are overwriting the previously defined value of value in line 61.


Longer answer: Consider this minimized example:

value = True
dictionary = {'foo': 'bar', 'baz': 'qwurx'}
for key, value in dictionary.items():
    print(key, value)
print(value, type(value))

Output:

# foo bar
# baz qwurx
# qwurx <class 'str'>

The issue is that you re-defined value in the loop on every call. The value-variable shadows and overwrites the outer one.


To find such things on your own next time: The error message is already a good hint. It tells you that the method expects a boolean value, but got a string instead. Now go back from the given line to find where the variable is set last…


Concerning coding style: Your code contains a lot of generic namings, like a dictionary called dictionary and variables called values. Think of more meaningful names to prevent such issues. See Clean Naming for further thoughts on this.

Answered By: Cpt.Hook
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.