Python Forum
TabError: inconsistent use of tabs and spaces in indentation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
TabError: inconsistent use of tabs and spaces in indentation
#1
Hello,

I am getting this error:

Error:
UbuntuUser@ubuntu:~/Desktop/PyQT$ python3 pycalc.py File "pycalc.py", line 80 for btnText, pos in buttons.items(): ^ TabError: inconsistent use of tabs and spaces in indentation
when running this code:

# Filename: pycalc.py

"""PyCalc is a simple calculator built using Python and PyQt5."""

import sys

# Import QApplication and the required widgets from PyQt5.QtWidgets
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QGridLayout
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QVBoxLayout
from functools import partial

__version__ = '0.1'
__author__ = 'Leodanis Pozo Ramos'

# Create a subclass of QMainWindow to setup the calculator's GUI
class PyCalcUi(QMainWindow):
    """PyCalc's View (GUI)."""
    def __init__(self):
        """View initializer."""
        super().__init__()
        # Set some main window's properties
        self.setWindowTitle('PyCalc')
        self.setFixedSize(800, 600)
        # Set the central widget and the genral layout
        self.generalLayout = QVBoxLayout()
        self._centralWidget = QWidget(self)
        self.setCentralWidget(self._centralWidget)
        # Create the display and the buttons
        self._createDisplay()
        self._createButtons()	
        
    def _createDisplay(self):
        """Create the display"""
        # Create the display widget
        self.display = QLineEdit()
        
        # Set some display's properties
        self.display.setFixedHeight(35)
        self.display.setAlignment(Qt.AlignRight)
        self.display.setReadOnly(True)
        
        # Add the display to the general layout
        self.generalLayout.adddWidget(self.display)
        
    def _createButtons(self):
    	"""Create the buttons"""
    	self.buttons = {}
    	buttonsLayout = QGridLAyout()
    	
    	# Button text | position on the QGridLayout
    	buttons = {'7': (0,0),
    	           '8': (0,1),
    	           '9': (0,2),
    	           '/': (0,3),
    	           'C': (0,4),
    	           '4': (1,0),
    	           '5': (1,1),
    	           '6': (1,2),
    	           '*': (1,3),
    	           '(': (1,4),
    	           '1': (2,0),
    	           '2': (2,1),
    	           '3': (2,2),
    	           '-': (2,3),
    	           ')': (2,4),
    	           '0': (3,0),
    	           '00': (3,1),
    	           '.': (3,2),
    	           '+': (3,3),
    	           '=': (3,4),
    	           }
    	
        # Create the buttons and add them to the grid layout
        for btnText, pos in buttons.items():
            self.buttons[btnText] = QPushButton(btnText)
            self.buttons[btnText].setFixedSize(40, 40)
            buttonsLayout.addWidget(self.buttons[btnText], pos[0], pos[1])
            
        # Add buttonsLayout to the general layout
        self.generalLayout.addLayout(buttonsLayout)
        
class PyCalcUI(QMainWindow):    
    # Snip
    def setDisplayText(self, text):
        """Set display's text. """
        self.display.setText(text)
        self.display.setFocus()
    
    def displayText(self):
        """Get display's text."""
        return self.display.text()
        
    def clearDisplay(self):
        """Clear the display."""
        self.setDisplayText('')

class PyCalcCtrl:
    """PyCalc Controller class."""
    def __init__(self, view):
    
        """Controller initiallizer."""
        self._view = view
    
        # Connect signals and slots
        self._connectSignals()
        
    def _buildExpression(self, sub_exp):
    
        """Build expression."""
        expression = self._view.displayText() + sub_exp
        self._view.setDisplayText(expression)
        
    def _connectSignals(self):
        """Connect signal and slots."""
        
        for btnText, btn in self._view.buttons.items():
            if btnText not in {'=', 'C'}:
                btn.clicked.connect(partial(self._buildExpression, btnText))
               
        self._view.buttons['C'].clicked.connect(self._view.clearDisplay)
                
# Client code
def main():
    """Main function."""
    # Create an instance of QApplication
    pycalc = QApplication(sys.argv)
    
    # Show the calculator's GUI
    view = PyCalcUi()
    view.show()
    
    # Create instance of the model and the controller
    PyCalcCtrl(view = view)
    
    # Execute the calculator's main loop
    sys.exit(pycalc.exec_())

if __name__ == '__main__':
    main()
I took the code from this website:
https://realpython.com/python-pyqt-gui-calculator/

I am trying for hours to fix the problem without any success. Do you see the error??
Reply
#2
The error message complains that a mix tabs and spaces are being used to indent code somewhere around line 80. I would look at the buttons dictionary. I used to get this error a lot when editing code in Notepad++ before I configured the editor to use spaces instead of tabs when editing Python code.

I cannot find where tabs are being used. I even copied the file to a file and wrote a Python program to look for tabs and found none. But it may be that the act of posting the code replaced the tabs with spaces.
hobbyist likes this post
Reply
#3
Copying from webpage may do some tricks so results are inconclusive but after pasting this code into Vim it was full of red. Every single empty line started with tabs, almost every conditional line ended with trailing whitespaces. (my vimrc is set to "Display tabs at the beginning of a line in Python mode as bad." and "Make trailing whitespace be flagged as bad.")

As I noted before - copying and pasting from webpage can do tricks but it would not hurt to go over file and correct where needed.
hobbyist likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
(Dec-26-2020, 09:15 PM)hobbyist Wrote: Hello,

I am getting this error:

Error:
UbuntuUser@ubuntu:~/Desktop/PyQT$ python3 pycalc.py File "pycalc.py", line 80 for btnText, pos in buttons.items(): ^ TabError: inconsistent use of tabs and spaces in indentation
when running this code:

# Filename: pycalc.py

"""PyCalc is a simple calculator built using Python and PyQt5."""

import sys

# Import QApplication and the required widgets from PyQt5.QtWidgets
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QGridLayout
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QVBoxLayout
from functools import partial

__version__ = '0.1'
__author__ = 'Leodanis Pozo Ramos'

# Create a subclass of QMainWindow to setup the calculator's GUI
class PyCalcUi(QMainWindow):
    """PyCalc's View (GUI)."""
    def __init__(self):
        """View initializer."""
        super().__init__()
        # Set some main window's properties
        self.setWindowTitle('PyCalc')
        self.setFixedSize(800, 600)
        # Set the central widget and the genral layout
        self.generalLayout = QVBoxLayout()
        self._centralWidget = QWidget(self)
        self.setCentralWidget(self._centralWidget)
        # Create the display and the buttons
        self._createDisplay()
        self._createButtons()	
        
    def _createDisplay(self):
        """Create the display"""
        # Create the display widget
        self.display = QLineEdit()
        
        # Set some display's properties
        self.display.setFixedHeight(35)
        self.display.setAlignment(Qt.AlignRight)
        self.display.setReadOnly(True)
        
        # Add the display to the general layout
        self.generalLayout.adddWidget(self.display)
        
    def _createButtons(self):
    	"""Create the buttons"""
    	self.buttons = {}
    	buttonsLayout = QGridLAyout()
    	
    	# Button text | position on the QGridLayout
    	buttons = {'7': (0,0),
    	           '8': (0,1),
    	           '9': (0,2),
    	           '/': (0,3),
    	           'C': (0,4),
    	           '4': (1,0),
    	           '5': (1,1),
    	           '6': (1,2),
    	           '*': (1,3),
    	           '(': (1,4),
    	           '1': (2,0),
    	           '2': (2,1),
    	           '3': (2,2),
    	           '-': (2,3),
    	           ')': (2,4),
    	           '0': (3,0),
    	           '00': (3,1),
    	           '.': (3,2),
    	           '+': (3,3),
    	           '=': (3,4),
    	           }
    	
        # Create the buttons and add them to the grid layout
        for btnText, pos in buttons.items():
            self.buttons[btnText] = QPushButton(btnText)
            self.buttons[btnText].setFixedSize(40, 40)
            buttonsLayout.addWidget(self.buttons[btnText], pos[0], pos[1])
            
        # Add buttonsLayout to the general layout
        self.generalLayout.addLayout(buttonsLayout)
        
class PyCalcUI(QMainWindow):    
    # Snip
    def setDisplayText(self, text):
        """Set display's text. """
        self.display.setText(text)
        self.display.setFocus()
    
    def displayText(self):
        """Get display's text."""
        return self.display.text()
        
    def clearDisplay(self):
        """Clear the display."""
        self.setDisplayText('')

class PyCalcCtrl:
    """PyCalc Controller class."""
    def __init__(self, view):
    
        """Controller initiallizer."""
        self._view = view
    
        # Connect signals and slots
        self._connectSignals()
        
    def _buildExpression(self, sub_exp):
    
        """Build expression."""
        expression = self._view.displayText() + sub_exp
        self._view.setDisplayText(expression)
        
    def _connectSignals(self):
        """Connect signal and slots."""
        
        for btnText, btn in self._view.buttons.items():
            if btnText not in {'=', 'C'}:
                btn.clicked.connect(partial(self._buildExpression, btnText))
               
        self._view.buttons['C'].clicked.connect(self._view.clearDisplay)
                
# Client code
def main():
    """Main function."""
    # Create an instance of QApplication
    pycalc = QApplication(sys.argv)
    
    # Show the calculator's GUI
    view = PyCalcUi()
    view.show()
    
    # Create instance of the model and the controller
    PyCalcCtrl(view = view)
    
    # Execute the calculator's main loop
    sys.exit(pycalc.exec_())

if __name__ == '__main__':
    main()
I took the code from this website:
https://realpython.com/python-pyqt-gui-calculator/

I am trying for hours to fix the problem without any success. Do you see the error??

I have already forked Python to have proper { } blocks and get rid of this fancy indentation rules. If there is anybody interested I can make my git become public or share the diff file. To be clear, the forked version can still continue to work on indented-style files, you can just decide every time you open a statement if you want to use the indent-style or { }.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Found buttonstate in tabs MacTommu 4 1,948 Sep-22-2021, 05:56 PM
Last Post: deanhystad
  [Tkinter] Vertical Tabs Alignment in Tkinter muhammadasim 2 5,914 Oct-05-2020, 08:40 AM
Last Post: Larz60+
  [Tkinter] Need help please properly putting tabs within a PanedWindow JackMack118 2 3,312 Dec-08-2019, 03:02 PM
Last Post: balenaucigasa
  [PyQt] Drag items across tabs Alfalfa 5 4,690 Sep-01-2019, 11:58 PM
Last Post: Alfalfa
  [Tkinter] Adding space between Notebook tabs Columbo 4 4,428 Jul-10-2019, 10:46 PM
Last Post: Columbo
  [Tkinter] How to get a tabs works exactly same as google chrome sarthak260 0 3,737 Mar-07-2019, 10:45 AM
Last Post: sarthak260
  [Tkinter] How to create multilple tabs in tkinter from different classes Rishav 5 18,182 Jul-11-2018, 11:59 AM
Last Post: CCChris91
  How to create mutiple tabs in tkinter using oops Rishav 2 6,824 Jul-12-2017, 04:43 PM
Last Post: Rishav

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020