Unbounded by a binding

Once upon a time, fresh out of Code Academy, I Googled for a way to design a GUI in Python. I came across Qt Designer. Cool! It reminded me of Microsoft Access and Visual Basic. I could lay out windows, buttons, boxes and so on just the way I wanted, set their properties and add some code. I began learning about “slots” and “signals”, Qt’s system of connecting what a widget is supposed to do to what the user does to it. But before long, it hit me:

The code I was using to create this wonderful GUI was not Python; it was Qt.

Somewhere along the line I’d read that Qt could be used to make a GUI for use in Python, yet Qt and Python are completely separate languages, so how, I asked myself, could I possibly use a GUI created in Qt, in Python? It sounded about as likely as running a Mac OS application on my Android phone. For whatever reason at that time, I couldn’t find a clear answer to this, and other options such as wxPython and Tkinter drifted into my view, so Qt was quickly forgotten. wxPython looked cool but when I decided it would be best for me as a newbie to learn in Python 3, wxPython quickly dropped off my radar. I noted Tkinter is included with Python and has been around forever, so it seemed to be the best option of the three. Unfortunately, I found Tkinter’s documentation to be fragmented and in some cases, ancient. Trying to produce a simple table object gradually wore me down over a period of months, which taught me the hard way that Tkinter is apparently just fine for GUIs with simple buttons, text boxes and lists, but nearly useless for data objects any more complex than a listbox. The one or two times I’ve run across table-like objects for Tkinter, I found they were not compatible with Python 3.

Luckily, I was only one more frustrated Google search away from discovering an amazing concept that brings diverse languages together in harmony, letting them play ball joyously with one another and get along like BFFs:

Bindings.

I eventually discovered Pyside, which re-introduced me to its friend Qt, and now Qt and I are buddies again! The secret? Lay out, code and design the GUI of my dreams in Qt, and when done, it’s only one magical command-line incantation away form being transformed into a Python class object, ready to be called upon any time! Pyside changed the direction of my DataQ project and injected it, and my Python learning adventure, with new life. Before long I was able to finally create a real GUI widget for my app and even able to my data into it.

Next step: wrapping my brain around model-view programming.

TableForm

My original mockup idea..


Capture

So close!

QTableView knocks Tkinter off the ‘table’

Capture

Hallelujah!

Have I got a deal for you! How about a GUI widget with over double the functionality, with less than half the code? Here it is:

import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtSql import *

# My function for assembling SQL queries for my 'transactions' table. I'll share the code another time.
from dq_sql import *

app = QApplication(sys.argv)

class DqTableForm(QWidget):
    def __init__(self, parent = None):
        super(DqTableForm,self).__init__(parent)

        self.setWindowTitle('Transactions')
        self.setMinimumWidth(950)
        self.setMinimumHeight(300)

        db = QSqlDatabase.addDatabase("QSQLITE")
        db.setDatabaseName("dataq.db")
        db.open()

        self.DqModel = QSqlQueryModel()

# My TransQry function takes parameters and returns a SQL query using the parameters as criteria for filtering my 'transactions' table.      

self.DqModel.setQuery(TransQry("2014-03-01","2014-03-31","DESC","","","202",""), db)

        self.DqTable = QTableView()
        self.DqTable.setModel(self.DqModel)
        self.DqTable.hideColumn(0)
        self.DqTable.resizeColumnsToContents()
        self.DqTable.resizeRowsToContents()

        grid = QGridLayout()
        grid.addWidget(self.DqTable,0,0)
        self.setLayout(grid)

form = DqTableForm()
form.show()
app.exec_()

See? Less than 45 lines. Sure beats the nearly 100-line, marginally useful alternative, which I have been sweating and struggling under for months. Lesson learned: there’s a very fuzzy boundary between challenging myself toward productive learning, and finding the most efficient solution to a need. In this instance, given the complex data filtering and sorting I’m trying to accomplish, Qt’s QTableView soundly beats anything Tkinter is even remotely capable of without astronomically more code. Shout out to Bo’s Qt GUI tutorials for introducing me to Qt, the documentation for the PySide Python Qt bindings for helping me figure out QTableView, and to my friend and constant companion Google, for helping me evolve.

Revolution! (tossing out Tkinter)

QtDesigner

Wow, a real, live Python visual app designer!

In the last few weeks I realized I have a long way to go to figure out how the MultiListbox code works…it seems like even the simple function of selecting a line of data requires torturous hand-coding. Almost two months after setting out on my quest for a Python data management application, I am still tripping and stumbling over a single GUI element. And yet all it does is display columns of data, something Microsoft Access does in its sleep, and the MultiListbox isn’t even editable. I’ve become distracted and discouraged. There are functions in the MLB class that I’m not even close to understanding, and there is no detailed explanation of the code anywhere. Lately I’ve thinking, there’s got to be a better way. There’s got to be a way where I can focus my coding on what I want the GUI widgets to DO, instead of struggling just to bring them into functional existence.

So, this afternoon, I once again Googled “Python GUI builder” or something like this and found this series of videos on building Python GUI applications with the Qt framework. https://www.youtube.com/user/Deusdies2.

The first series of videos walk the user through how to download and install a Python interface to the Qt development framework, in this case PySide. The author of this video series uses PyCharm on Windows 7, so his desktop and mine are nearly identical, meaning it couldn’t be easier to follow along with him.  The first few videos walk through the creation of simple Qt-based GUI applications such as a calculator. Eventually it moves on to QtDesigner, which, wonder of wonders, is a “drag and drop” GUI designer very much like Microsoft Access and Visual Basic. Where Tkinter requires 100% hand-coding of just about every step of a widget’s function, even PySide coding by itself without the graphical Qt Designer seems much simpler and less labor intensive.

Yes, I have spent many months on Tkinter. Yes, it seemed like I was on the right track when I discovered the MultiListbox. I enjoyed, for a time, the challenge of trying to figure it out. But somewhere along the line, it wasn’t fun anymore. It was a chore. This made it all too easy to become distracted with other projects. That was the signal that something was wrong. I like a challenge and I have loved learning Python, but when it’s no longer enjoyable, it’s no longer worth doing.  It’s a little intimidating to think of learning a completely new GUI builder.  However once I saw that drag and drop designer, that shimmering promise of instantly knowing my app will look the way I want it to without all the trial and error, and each item I drop into my app already knowing how to do what it’s supposed to and all I have to to is give it parameters,  I thought, “This could make Python fun again.” So off I go on my next, unexpected Python path. I’m going spend the next phase of my Python adventure getting as much as I can out of Mr. Milanovic’s videos, and of course, sharing the results.

A slow but sure learning process

It would be easy to grab a chunk of someone else’s code, modify it only as necessary, and through a lot of trial and error get it to do what I want.  That is what I originally set out to do when I discovered the MultiListbox custom widget in this project. Using this method I might be able to patch together something functional, without ever learning in depth about how the code actually works. This course of action is a continual temptation to my impatient self, especially now as I am grappling with the most complex GUI object in my DataQ application.

But that is not my goal. I don’t just want to learn how to use Python for specific tasks; I want to learn how Python WORKS. The MultiListbox fascinated me because it’s not just any old Tkinter widget; it’s a custom widget made out of other widgets — in this case, a series of Listboxes put together to display rows of data. In examining the MultiLisbox code, I realized I knew very little how even a single Listbox works, let alone a group of them squashed together and synchronized. I therefore decided to learn about and experiment with Listboxes, learning how they work from the ground up. I have found it hard to stay focused. Sometimes I get away from Python completely for days at time because my brain just feels fried by it.

Despite the challenges, I’m happy to report that I’m making progress. I’ve even started designing my very own MultiListbox class (mostly) without even looking at the original code! My version makes each individual column in the MultiListbox its own class, and I use the .grid() geometry manager instead of the often unpredictable .pack(). Here is the ‘rough draft’: Rob’s MultiListbox.

I do not look favorably upon a certain brand of canned, processed meat product

As of today, I am no longer allowing comments or user registrations on this blog.

The image below sums up the reasons.  Out of the hundreds of “comments” (in quotes because they don’t even deserve to be called such) I have received, I can count on the fingers of one hand the number that are from actual readers of this blog who have something to contribute.  The same goes for “user” registrations.

I wish I could devote all my working hours to my Python learning and this blog, and if that were the case, perhaps I would think differently.  However, I have a full-time job that is not Python related, a wife, and numerous other family and social commitments that are important to me.  I simply don’t wish to devote the time to moderating “canned lunch meat”, and I certainly don’t want to spend even a penny on software to do it for me.

For those real humans out there who have been following this blog, especially those who have commented, thank you for your support and please accept my apologies. Feel free to contact me through Google Plus or Twitter if you have any feedback or suggestions regarding the blog.

I_d8dd4a_105979

Becoming an SQL squirrel

The first chapter of my quest was the hunt for a suitable GUI element to display data in columns. I eventually settled on the Multilistbox, a custom widget I found that was created using the standard Tkinter Listbox widget. I then enthusiastically dove into learning all I could about Tkinter. This revealed the need to thoroughly test my Multilistbox with real-world data..of which I had none. Then I focused on methods of getting data into my DataQ app, which led to experimenting with code to parse data from text and CSV files. Before I knew it I was off on multiple, simultaneous rabbit trails, including trying to figure out how to parse data from Evernote notes. Before I knew it, I was wandering aimlessly and making little progress.

Now I’ve decided to focus back on the original goal: financial management. This would be, by far, the most useful function for me, something I would use on a daily basis. It will also be instructive for other possible uses for DataQ. I therefore have now imported all 3000+ of my financial transactions from my Microsoft Access database to Sqlite. I’m laying aside the GUI for now and focusing on the heart and soul of DataQ which is data! I need to learn how to get the data I want using queries, something I’ve had passing acquaintance with through MS Access, but don’t know thoroughly because Access lets me build queries graphically. That’s great for getting results quickly, not so great for learning.

I have two tables: ‘transactions’ and ‘accounts’, with the following structure:

    transactions

TransactionID * Integer primary key
Date
PayeeOrName
TransactionDescription
Category * Income or expense category. In correct bookkeeping terminology, also an ‘account.’
Income * Amount
Expense * Amount
Account * Asset or liability account, ex: checking, savings, credit card

    accounts

AccountNum * Integer primary key
AccountDescription
AccountType * Asset, liability, income, expense
Clear * 1 = transaction has cleared the bank, 0 = not cleared.

Both the ‘Category’ and ‘Account’ fields contain an ‘AccountNum’ from ‘accounts.’ Every transaction query includes a calculated field called ‘Net’ which subtracts the ‘Expense’ amount from the ‘Income’ amount, giving the net effect on the account balance. A typical SQL query will look like the following, which displays all transactions in descending order from most recent:

SELECT transactions.Date, transactions.PayeeOrName, transactions.TransactionDescription, accounts.AccountDescription AS Category, transactions.Income, transactions.Expense, (transactions.Income - transactions.Expense) AS Net, accounts_1.AccountDescription AS Account, transactions.Clear
FROM (transactions INNER JOIN accounts AS accounts_1 ON transactions.Account = accounts_1.AccountNum)
INNER JOIN accounts ON transactions.Category = accounts.AccountNum ORDER BY transactions.Date DESC, PayeeOrName ASC

The data source for the Multilistbox will be obtained by queries such as this, so I think it’s time I get to know Sqlite better.

The twisting, turning path to PYTHONPATH

Wow. The learning process sure is messy, and at times embarrassing.

Here’s how it all started:

I have a folder called ‘tools’ which contains various modules I wrote that I want to be accessible for import to all my Python projects. One of these modules is called ‘DbSession’ — it contains a class for handling various Sqlite database tasks. Each Python project is in its own folder, with the ‘tools’ folder as a ‘sibling’ under the same parent directory, as in this example:

C:\MyPath\Dropbox\projects\tools
C:\MyPath\Dropbox\projects\ProjectA
C:\MyPath\Dropbox\projects\ProjectB

I use Dropbox to sync my projects between two computers, one running Windows XP and one running Windows 7. The path to the Dropbox folder is different on each PC. No matter which PC I’m using, I want the modules in ‘tools’ to be accessible for importing to all my projects.

As previously posted, my first solution was to do a sys.path.append() in my code, but afterward I learned this was not the best solution because it would involve changing my code every time I switched computers or re-arranged directories. I then decided I’d like to be able to set the PATH in each PC appropriately so the imports will work on both without changing my code. After much Googling and sifting through what seemed to be a multitude of possible answers, I found what I *thought* was the solution, but upon further testing, discovered I was mistaken. I thought making the imports work in my project directories was just a matter of adding my ‘tools’ directory to the PATH variable. Here’s what I did (Windows XP machine):

Added ‘tools’ directory to PATH variable and confirmed it is set correctly by typing “PATH” on a command line:

C:\>PATH
PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32
\WindowsPowerShell\v1.0\;C:\Python33;C:\Python33\Lib\site-packages;C:\Documents
and Settings\Rob\My Documents\Dropbox\projects\tools

The ‘tools’ directory contains a test ‘Hello World’ program, ‘hello.py’, which I can run from the C:\ directory just by typing the file name. This proves the PATH variable is set correctly to ‘tools’:

C:\hello.py
Hello, world!

..although if I try to run ‘hello.py’ from Python, Python can’t find it!

C:\python hello.py
python: can’t open file ‘hello.py’: [Errno 2] No such file or directory

Here’s my attempt at importing from the module ‘DbSession.py’, which resides in ‘tools.’ First, I ran Python from the C:\ directory. It can’t find the ‘DbSession’ module in ‘tools’, even though the above test with ‘hello.py’ at least showed the ‘tools’ directory was correctly set in PATH. I tried putting a blank ‘__init__.py’ file in ‘tools’, but it still didn’t work:

C:\python
Python 3.3.4 (v3.3.4:7ff62415e426, Feb 10 2014, 18:12:08) [MSC v.1600 32 bit (In
tel)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.
>>>from DbSession import DbSession
Traceback (most recent call last):
File ““, line 1, in
ImportError: No module named ‘DbSession’

When I ran Python from the ‘tools’ directory the import worked fine, proving there’s no problem with the module itself:

c:\Documents and Settings\Rob\My Documents\Dropbox\projects\tools\python
Python 3.3.4 (v3.3.4:7ff62415e426, Feb 10 2014, 18:12:08) [MSC v.1600 32 bit (In
tel)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.
>>>from DbSession import DbSession
>>>

So what’s up? I KNOW I set the PATH right…how come Python can’t import from the ‘tools’ directory into a project directory, when I can run the ‘hello.py’ code, which is also in ‘tools’, from any directory I want? This seemed so insane it tempted me to go back to using sys.path.append().

Until I ran across this one little nugget, in a 5-year-old article, on a site I’d never heard of:

“However, unlike PATH (which tells the operating system which directories to look for executable files in), PYTHONPATH is used by the Python interpreter to find out where to look for modules to import.”

BINGO! EUREKA! HALLELUJAH!

So, I need TWO SEPARATE PATH VARIABLES…the PATH variable to help Python find itself and its various packages:

path

..and the PYTHONPATH variable to help it find modules for importing!

pythonpath

I don’t know if it’s my misfiring brain, but somehow in all my recent travels, this simple truth eluded me. So, now my jolly good mates at Stereoplex have been blessed with a mention and a backlink. Cheers!

From knowledge import improvement

2014-04-02 UPDATE: The only reason ‘from tools.DbSession..’ (see below) worked was because ‘tools’ was a subdirectory of the directory I was in (‘projects’). Had NOTHING do to with the PATH variable. I FINALLY found the solution!

In my post about importing Python modules, I wrote that I preferred setting the PATH variable in my code instead of changing my computer’s PATH variable. With so much of my code being new, that did not seem like much of a burden. It was, however, pointed out to me that it could become a major hassle down the road, if I have tons of scripts set to a certain path using sys.path.append(). They would all need to be updated if used on a computer with a different directory structure, or even if I just moved my code around on my current computer. I had previously tried working with the PATH setting without success, so for the time being it was easier to specify it in code.

Now, I am happy to report, I have discovered the better way.

I have a class called ‘DbSession’ in the module ‘DbSession.py.’ I keep it, and other modules that I want to share among all my projects, in a directory called ‘tools.’ Project-specific code is kept in project folders which reside in the same parent directory as does ‘tools.’

Here’s how I figured it out how to make ‘DbSession’ available to all:

First,  I added the ‘tools’ directory to my system PATH variable and confirmed it was correct. Here is is displayed in a command prompt window, including my ‘tools’ directory:

echo %PATH%
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;
C:\Python33;C:\Python33\Lib\site-packages;
C:\Documents and Settings\Rob\My Documents\Dropbox\projects\tools;

I run Python from the ‘tools’ directory and confirm the import works, without errors (that is, it does nothing but put me back to the Python prompt), from there:

>>>from DbSession import DbSession
>>>

I run Python from a different directory (‘projects’) and retry the import. It chokes:

>>>from DbSession import DbSession
Traceback (most recent call last):
File “”, line 1, in
ImportError: No module named ‘DbSession’

Huh? I thought I had the ‘tools’ directory in my PATH variable, so shouldn’t Python be able to see what’s in it?

Behold, the kicker:

>>>from tools.DbSession import DbSession
>>>

And there we have it! Apparently, when a directory for modules is specified in PATH, the name of that directory must also be specified in the import statement when attempting to access those modules.

Now, at last, I’ve found the right path to the right use of PATH.

Importance of importing, without imploding

2014-04-02 UPDATE: I found a a much better way to solve this problem.

I have spent the better part of a day, and several rounds of digging at Stackoverflow, to figure out the solution to this issue. It was so tricky (for my middle-aged brain at least) that I want to share it with the world in as simple and straightforward a way as possible in the hope I save some fellow newbies some aggravation.

The more I code, and the more problems I solve with code, the more I don’t want to have to solve the same problem more than once. I’ve tasted the elegant efficiency of re-using code. Once I have a piece of code “perfected” I want to put it in a directory that I can access from any of my projects. How can I share code among several projects in different directories? Here’s my example:

I have two project directories and a directory called “tools” that contains a module “coolstuff.py”. All three directories are subdirectories of ‘Projects.’ “coolstuff.py’ contains a function also called “coolstuff.” I want to be able to import and use the “coolstuff” function in either of my project directories.

c:\mypath\projects\ProjectA\spam.py
c:\mypath\projects\ProjectB\eggs.py
c:\mypath\projects\tools\coolstuff.py

Contents of coolstuff.py:

def coolstuff():
    """
    This is a cool function you should use often.
    """
    print ("Cool function activated!")

I want to be able to call “coolstuff()” from either “spam.py” or “eggs.py.” Obviously I need an import statement. I started off with just ‘import coolstuff’, but that didn’t work. I’ll spare you the gory details of what I went through to find this solution, but suffice it to say, it involved just about every version of “from … import ….”, “import….”, etc., so I’ll just skip straight to the answer:

Contents of ‘spam.py’:

import sys
sys.path.append('C:/mypath/projects/tools')
from coolstuff import coolstuff
coolstuff()

The “sys” module allows run-time addition to the “PATH” environmental variable using the ‘sys.path.append’ statement. This allows the ‘import’ statement to find ‘tools’ and whatever is in it.

Since the function I want is ALSO named ‘coolstuff’, I have to reference it to the right of the import statement. When I finally got the path issue solved so that the statement ‘import coolstuff’, by itself, went error free, I got a ‘module object is not callable’ error when I tried to actually use the function. Turns out, of course, that the FILE ‘coolstuff’ is the ‘module object’, and the FUNCTION ‘coolstuff’ inside the FILE ‘coolstuff’ has to be called in order to work, hence: ‘from coolstuff import coolstuff.’

For the time being, I prefer to name my modules with the same name as the functions they contain, so that one glance in the ‘tools’ directory is all I need to find the function I want. I prefer to set the “PATH” variable at runtime so I don’t have to monkey with my PC’s environmental settings manually ever time I move code to a different folder.

Hope this clears things up for anyone who was similarly vexed.

A Quest Begins

I recently stumbled across two little applications that, along with my recent advances in figuring out Tkinter, have finally given a much needed boost of inspiration — and a goal to strive for.

First there was this:

phoneapp

This is a step-by-step tutorial for a simple phone list using Tkinter and SQLite.  The user selects a name from the list and presses the “Load” button to load it into the form at the top.  The form is used to make changes to the data; the list is just for viewing and selecting.  This is what I have wanted to accomplish, boiled down to its absolute simplest level.  This little app also answered a big question for me; how do I get data from an SQLite database table into a Tkinter form for viewing and editing?  The short answer: the Tkinter Listbox widget, which has an INSERT method.

Even better, I found this:

inventory

Now we’re talking! Even though it’s a bit buggy, it’s the closest thing I have yet seen to what I have wanted to accomplish. It’s got a system of relational tables: customers, invoices and items. It has forms that are called when the user wants to add or change data. But its most intriguing item is a custom widget called a MultiListbox:
multilist

I found this object fascinating, because it opened my eyes to the power of Tkinter. It’s actually possible to make custom widgets out of the basic ones provided. The MultiListbox is a set of regular Listboxes squashed together in a frame and synchronized. It lines up each data field in its own column. It accepts data input in the form of tuples, for example: (‘Date’,’Item Number’,’Quantity’,’Price’). Each tuple is a row of data in the MultiListbox.

So, now, at last, I’ve found my quest!

holygrail

I plan to build an app around two basic objects: what I call a “TableForm”, for filtering, viewing and selecting data….
TableForm

..and what I have named a “RecordForm”, which will be used to edit, add, delete or update a record…
RecordForm

These two base objects could be duplicated for each table in the underlying SQLite database.

So here’s the short version of my plan. I’m starting with the coding of the TableForm, since it’s really the heart of my app. I have broken the Table Form down into component classes, starting with the MultiListbox (the most complex part). I plan to code and test each object separately, then piece them all together to make the TableForm class. I’ll then repeat this process with the RecordForm. This rudimentary data management setup could be applied to an endless array of applications, from personal finance to getting data from the Web to tracking my running

In true Python spirit, I wanted to name my app “DataQuest”, but found out there is a company called Dataquest. I didn’t want to get in trouble with them or cause confusion, so I’ve decided to call my app “DataQ.” I can already see the most time-consuming part of development is just figuring out how stuff works. When I first saw the code for the MultiListbox, it might as well have been in Chinese. It has taken some in-depth study of my Tkinter links and a lot of trial-and-error experiments with the code to get it deciphered. I feel like one of the great seafaring explorers of the 15th and 16th centuries, crossing a turbulent, uncharted ocean to a new world, or a biologist trying to decode DNA sequences.

See below for what I have so far in my version of the MultiListbox base class, along with comments I wrote in the code that explain the various parts as I was able to figure out what they did.

# A custom widget consisting of multiple Listbox widgets, with each listbox containing a column of data.
# Based on MultiListBox code used by suhailvs@gmail.com (https://sourceforge.net/projects/pyinvoice/)
# The code I was able to figure out is explained in the comments.
# Functions with comment ???? are ones I haven't figured out yet.

from tkinter import *
class MultiListbox(Frame):
    '''MultiListbox made by Labels as table header and Listbox as table columns'''
    def __init__(self, master, lists):
        Frame.__init__(self, master)
        self.lists = [] # A list of listboxes
        self.footers = [] # List of listbox footers
        for l,w in lists: # l=label, w=width for each listbox
            # Each listbox gets its own frame
            frame = Frame(self); frame.pack(side=LEFT, expand=YES, fill=BOTH)

            # Label = listbox name
            Label(frame, text=l, borderwidth=1, relief=RAISED).pack(fill=X)

            # Create each listbox
            lb = Listbox(frame, width=w, borderwidth=0, selectborderwidth=0,
                 relief=FLAT, exportselection=FALSE)
            lb.pack(expand=YES, fill=BOTH)

            # Add a footer for each listbox. Available for calculated totals.
            footer = Label(frame)
            footer.pack(fill=X)

            # Lists = list of numerical references to each listbox (ex .43982632.44021632.44021744.44022080)
            # Keeps track of listboxes after they are created.
            self.lists.append(lb)
            self.footers.append(footer)

            # Each listbox gets these bindings

            # left mouse button pressed. Required so left click selects entire line.
            lb.bind('', lambda e, s=self: s._select(e.y))

            # double click will eventually be what brings up the transaction edit form.
            lb.bind('', lambda e, s=self: s.double_click())

            # These came with the original MLB code but don't seem to do anything.
                #lb.bind('', lambda e, s=self: s._select(e.y)) # left mouse button pressed while moving
                #lb.bind('', lambda e: 'break') # mouse pointer leaves the widget
                #lb.bind('', lambda e, s=self: s._b2motion(e.x, e.y))
                #lb.bind('', lambda e, s=self: s._button2(e.x, e.y)) #right mouse button pressed

        # The frame that will contain the individual list boxes, each with its own frame (see above).
        frame = Frame(self); frame.pack(side=LEFT, fill=Y)
        Label(frame, borderwidth=1, relief=RAISED).pack(fill=X)
        sb = Scrollbar(frame, orient=VERTICAL, command=self._scroll)
        sb.pack(expand=YES, fill=Y)

        # lists[0] = the first (left most) list box.
        self.lists[0]['yscrollcommand']=sb.set

    def double_click(self):
        print(self.item_selected)

    def _select(self, y):
        row = self.lists[0].nearest(y) # integer index of selected row

        # Calls the selection_clear function to un-select whatever row was selected before left button was clicked.
        self.selection_clear(0, END)

        # Calls the selection_set function to select the line clicked on.
        self.selection_set(row)
        return 'break'

    def _button2(self, x, y): #????
        for l in self.lists: l.scan_mark(x, y)
        return 'break'

    def _b2motion(self, x, y): #????
        for l in self.lists: l.scan_dragto(x, y)
        return 'break'

    def _scroll(self, *args): #????
        for l in self.lists:
            l.yview(*args)

    def curselection(self): #????
        return self.lists[0].curselection()

    def delete(self, first, last=None):
        for l in self.lists:
            l.delete(first, last)

    def get(self, first, last=None):
        result = []
        for l in self.lists:
            result.append(l.get(first,last))
        if last: return list(map(*[None] + result))
        return result

    def index(self, index):
        self.lists[0].index(index)

    def insert(self, index, *elements): #Elements = the fields in a row.

        # Loop through each field in the row
        for e in elements:

            # Each field will have an index number. Ex: e[0] = ID, e[1] = Date, etc.
            i = 0
            for l in self.lists:
                # Insert each field in its applicable list box
                # Insert a blank if the field is None, otherwise boxes won't align.
                if e[i] == None:
                    l.insert(index, " ")
                else:
                    l.insert(index, e[i])
                i = i + 1

    def size(self):
        return self.lists[0].size()

    def see(self, index):
        for l in self.lists:
            l.see(index)

    def selection_anchor(self, index):
        for l in self.lists:
            l.selection_anchor(index)

    def selection_clear(self, first, last=None):
        # Unselects the entire line by looping over each of the list boxes that make up the MLB.
        for l in self.lists:
            l.selection_clear(first, last)

    def selection_includes(self, index):
        return self.lists[0].selection_includes(index)

    def selection_set(self, first, last=None):
        # first = the index of the selected row

        # self.item_selected = a list whose 1st item is the index of the row, followed by the entire row.
        # Example:
        # [6,134,'2014-02-03','Publix','',188,'$0.00','$3.48',197,1]

        self.item_selected=[first,]+self.get(first)

        for l in self.lists:
            # Sets the selection to the same row in all list boxes
            l.selection_set(first, last)

    def not_focus(self):
        for l in self.lists:
            l['takefocus']=False

    def calc_total(self,column):
        # Returns the total of the selected column number. Column must contain numeric values only.
        total = 0
        for n in range(0,self.lists[column].size()):
            total = total + float(self.lists[column].get(n))
        return total

    def footer_val(self,column,value):
        # Sets the text to be displayed in the footer of the column specified.
        v = StringVar()
        self.footers[column].config(textvariable=v)
        v.set(value)

If you scrolled all the way through that huge block of code to get here, I’ll bet you are the kind of person who sits in a movie theater and waits for all the credits to finish, hoping for something fun or entertaining at the end, or a sneak peak at a new movie. So as to not disappoint you, here’s an relevant item:
Monty-Python-and-the-Holy-Grail-monty-python-and-the-holy-grail-4968359-845-468