Tag: Tkinter

Entering data in Python: console or GUI

Entering data in Python: console or GUI

Suppose you want the user to enter some data for a Python program to work on. For this, Python provides the input statement, which can print out a prompting string and wait for keyboard input. 

name = input("What is your name? ")
print("Hi "+name +" boy!")

This little program asks for your name and waits for you to type a string and press Enter. The input statement accepts keyboard input and returns a string. So, the resulting console results might look like this:

What is your name? Jim
Hi Jim boy!

Heinlein fans may recognize the reference.

You can paste that 2-line program into any development environment, such as Thonny, PyCharm or even Jupyter Notebook and see it work right away.

Adding two numbers

Of course, you can enter numbers as well, but you must be sure to convert the resulting strings into an int or a float. Here we use the more general float.

x = float(input("Enter x: "))
y = float(input("Enter y: "))
print("The sum is: ", x+y)

The resulting output is:

Enter x: 23.45|
Enter y: 41.46
The sum is:  64.91

Of course, this naïve program expects only legal input. If you enter, say, “qq” instead of 22, you will get a Python error:

File "C:\Users\James\PycharmProjects\input\inputdemo.py", line 7, in <module>    
y = float(input("Enter y: "))
ValueError: could not convert string to float: 'qq'

There are ways to check for this, of course, such as catching Exceptions, and we will explain those in the following example.

However, you will only find the input statement in rudimentary examples. Most programs that need user input get it from a windowing interface. We’ll show these same examples next using the tkinter GUI library.

Making a windowing example program

You can do much the same thing by using the Entry field in the tkinter GUI (graphical user interface). Here we repeat those examples in simple tkinter windows.  To use tkinter, you have to import that library into your program:

from tkinter import *
import tkinter as tk

You also create an abbreviation for tkinter, naming it just tk.

Then, most of the setup code creates the visual widgets and their arrangement. In the following example, we use an Entry field, a Button and two Labels. You start by getting the window system pointer tk.Tk() and use it to attach the widgets to. After you create this objects, you run the mainloop() function which displays the window and receives mouse and keyboard input. The window keeps running until you close it by clicking on the “X” in the upper right corner or selects some widget that causes the window to close.

Our first example above was one where you enter your name and it says Hello back, again giving homage to Heinlein in the process. The tkinter program does the same thing

The code for this program creates the two labels, the Entry field and the OK button:

def build(self):
    root = tk.Tk()
    # top label
    Label(root,
         text="""What is your name?""",
         justify=LEFT, fg='blue', pady=10, padx=20).pack()

    # create entry field
    self.nmEntry = Entry(root)
    self.nmEntry.pack()   # and put it into the window

    # OK button calls getName when clicked
    self.okButton = Button(root, text="OK",
                            command=self.getName )
    self.okButton.pack()

    # This is the label whose text changes
    self.cLabel = Label(root, text='name', fg='blue')
    self.cLabel.pack()
    mainloop()      #run loop until window closes

When you click on the OK button, it calls the getName method, which fetches the text from the entry field and inserts it into the bottom label text.

# gets the entry field text
# places it on the cLabel text field
def getName(self):
   newName = self.nmEntry.get()
   self.cLabel.configure(text=“Hi “+newName+” boy!”)

Adding two numbers

And our second example rewritten from above reads two Entry fields, converts them to floats and puts the sum in the lower label.

 The code for this window is much the same, except that we fetch and add two numbers. Here is the function the OK button calls.

xval= float(self.xEntry.get())
yval = float(self.yEntry.get())
self.cLabel.configure(text="Sum = "+str(xval+yval))

Catching the error

However, if you enter some illegal non-numeric value, you can catch the exception and issue a error message:

try:
    xval= float(self.xEntry.get())
    yval = float(self.yEntry.get())
    self.cLabel.configure(text="Sum = "+str(xval+yval))
except:
    messagebox.showerror("Conversion error",
                              "Not numbers")

If you enter non-numeric strings, the program displays this message box:

And that’s all there is to creating a program with a simple graphical user interface.

Comparing Python Tkinter and PyQt5

Comparing Python Tkinter and PyQt5

TkInter is the well-known GUi system based on the Tk toolkit and interfaced to Python so that it has become the preferential GUI interface system. PyQt5 is an analogous user interface developed and support by Riverbank Computing, and is essentially a set of bindings for the QT platform developed by the Qt company. PyQT5 is available under a GNU GPL v3 license, or as a commercial license. This essentially means that you can use PyQt5 freely, but you must distribute your source code with any product you build using PyQt5. Or, you can buy a commercial license.

GUI using Tkinter

GUI using PyQt5

The two figures above show the same interface developed in Tkinter and PyQt5. They show that you can build pretty much the same kind of GUI with either system.  I spent a week learning PyQt5 and building the new interface to match the one I had already built in Tkinter. Each system has different advantages and disadvantages, and we’ll summarize them in the article that follows.

The tkinter version is fully integrated with the database, but I only bother to connect the right hand searchbox and listbox to the database in PyQt5. The rest are just hardcoded,

But basically, the systems do about the same things and are about equally easy (or hard) to use, and you can’t go wrong using either of them. There was no clear winner of this experiment: once you have climbed the learning curve you can build nice-looking systems either way.

I built the Tkinter version of this interface as part of a larger development project to interface our opera company’s data to a new MySQL database, where building a UI gave us the ability to view the information in more flexible ways. This screen represents a way to create a cast list for the current and previous shows and generate spreadsheets of those casts for the Board , the cast and the directors to work with. The left-hand table is the final cast, sorted by role-type and sex, which amounts to one simple database query.

It allows you to select any person in our database and assign them a role in the current or an older production.

I learned how to use PyQt5 from the on-line PyQT5 reference guide as well as from this short tutorial by Michael Herrman. He has also written a book on PyQt and there is a link to it at the bottom of the tutorial.  The Zetcode tutorial was also helpful. There is also a video tutorial at learnpyqt.com.

If you want to build a GUI using listboxes, buttons and checkboxes, you won’t have any trouble with PyQt. In fact, since the listbox automatically includes a slider, you will find it a bit easier.  It is also worth noting that all PyQt widgets have Tooltips: helpful phrases that can explain what a widget is for.

I already noted that the QRadioButtons work better if you derive a class that holds the button index or title, using a Mediator pattern.

Layout managers

Tkinter has two major layout managers, pack() and grid(). Pack arranges the objects in the frame you provide. Grid allows you set up an n x n  grid and place the objects in one or more grid cells.

PyQt5 has three layout managers: QHBoxLayout, QVBoxLayout and QGridLayout. You can add widgets to the box layouts and they will line up horizontally or vertically. The QGridLayout is similar to, but not the same as, the tkinter grid. The biggest single difference is that if you place a widget in a grid cell, it expands to fill the entire cell. In order to put a button in a grid and not have it stretched to fill the cell, you have to add a QHBoxLayout inside the cell and then perform a hbox.addStretch(1) before and after the button to center it. These are essentially spacers that grow to fill the space on either side of the widget.

QtDesigner

PyQt5 provides the QtDesigner app which allows you create layouts visually. It actually includes layouts, and you can at least look at what code it generates. However, the resulting file is of type .ui and you have to run the pyuic5.exe program to convert the .ui file to a Python file. Once you have done this and edited the Python file, you can never go back to the designer.

Events in Qt5 are referred to as signals and slots, where the event is a signal and the callback function is a slot.  You can easily write analogous programs in PyQt5 to handle events much as you do in tkinter. You can also do this in the QtDesigner, but the event interface in the designer is a lot of trouble to use. Writing the code yourself is easier, and you probably would want to modify the code anyway. And, again, once you change the code, you can’t do back to the designer.

PyQt5 Style Sheets

While PyQt5 widgets have a plethora of useful methods, the designers left out such things as changing colors and borders. For this you have to resort to CSS (Cascading Style Sheets).  You can find a whole web page of Qt5 CSS examples here.

For example, suppose you want a label to be blue instead of black. In tkinter, you would write:

lb1 = Label(cFrame, text="Character", foreground='blue')

But in PyQt5, you would have to write.

lb1 = QLabel("Character")
lb1.setStyleSheet("QLabel { color : blue; }")

This sets the style for all instances of QLabel, but you can specify an individual label as well.

A more difficult case was setting the border of the GroupBox (which is the same as a tkinter LabelFrame). I also changed the color of the text label here too.

self.app.setStyleSheet("""QGroupBox {border:1px solid black;
    margin-top: 10ex;  padding: 15 3 px; }""")
self.setStyleSheet("QGroupBox::title {"
                     "color: blue;"
                    "background-color: transparent;"
                    "padding-top: -50px;"
                    "padding-left: 8px;} ");

Setting these style sheets can be tricky because you do not get any errors if you leave something out, like that terminal semicolon.

Listboxes and Model-View-Controller

PyQt5 has a list box, a table widget and a separate Treeview widget. While each of them can be used as stand-alone widgets, they also can be used in the Model-View-Controller system, where the data is the Model, the widget is the View and the Controller is the user or some external event. Essentially this is useful when the data changes frequently and this will cause your table to be refreshed automatically. I haven’t tried this out yet, as it takes quite a bit of programming. However, there are list and table widgets you can use without getting into using MVC.

I found the table display troublesome, because while you could remove the gridlines and left hand column numbers, the lines were quite widely separated.  After consulting the informants on Stackoverflow, I found that you could code the line spacing a line at a time. It turns out that the height of each row is calculated from the top of the table, so for each row, you have to calculate it as follows:

self.castTable.setRowHeight(row, (row + 2) * 7)

It turned out, however, that the spacing in the Treeview looks a lot better, and I am switching to that.

Conclusions

Tkinter is better documented and may a bit easier to work with. But there are more widgets in the PyQt5 library, including date editors, a progress bar, a slider, a font picker, a toolbar, and a multiline text entry field. It also supports the MVC pattern and includes Tooltips, which might be helpful for new users. While Herrman felt there was a difference in the clarity of the widgets, I didn’t notice it.