Tag: Tkinter

Rock, Paper, Scissors in Python: Part III – Improving the GUI

Rock, Paper, Scissors in Python: Part III – Improving the GUI

In our previous article, we developed a simple Python tkinter user interface for a rock[paper-scissors game. However, if you tried the code, you might stumble on one infelicitous problem:

No buttons selected

The program comes up with no boxes checked, but if you click on the Play button, the program plays a game anyway, assuming that Scissors had been selected. Why does this happen?

When we set up the 3 radio buttons we set the IntVar to -1 so that none of the buttons would be selected.

ChoiceButton.gvar = IntVar()
ChoiceButton.gvar.set(-1)   # none selected
ChoiceButton(lbf, "Paper", 0).grid(row=0, column=0, sticky=W)
ChoiceButton(lbf,"Rock", 1).grid(row=1, column=0,sticky=W)
ChoiceButton(lbf, "Scissors", 2).grid(row=2,column=0, sticky=W)

But let’s see what happens when our code checks the index to see which button is selected:

# play one game
def playit(self):
    index  = int(ChoiceButton.gvar.get())
    self.play = Player.moves[index]

The index returned is -1 as expected. And the three moves are in a tuple:

moves=("P", "R", "S")   #tuple of legal play characters

 And what do we get when we ask for

Player.moves[-1]

Python is unusual among common computer languages in that indexes of less than zero in arrays (lists), strings and tuples mean start at the end and work backward. So the index of -1 gives us the character ‘S’ and -2 would get us ‘R’ and so forth. This also rotates around so that -4 would give us ‘S’ again. In other words, Python apparently takes the index modulo the length of the array so that negative indexing never gives us a  out of bounds error. If we had set the gvar to 3 or more, no radio button would have been selected, and an error would occur.

So, how do we prevent this infelicitous behavior, where a player can click on the Play button when no radio button has been selected?  It would be possible to trap this out-of-range indexes and prevent play from taking place, but since the program assumes that only legal plays can occur, this would take a good deal of careful checking.

Instead, we do what we should have done in the first place and disable the Play button until a radio button has been clicked.

playButton['state']=DISABLED

But how do we turn the button back on?  We recommend using a Mediator.

The Mediator Pattern

The Mediator Design Pattern is a really simple little software trick that keeps classes from having to know about the internal workings of other classes. And when you are dealing with GUI widgets, there might be a number of GUI classes that needn’t know about each other.

Instead, we create a Mediator class and tell it about the push button and the radio buttons, and let it do the work. The Mediator keeps a reference to the pushbutton and receives a call when a radio button is clicked.  The whole thing is just a few lines of code:

class Mediator() :
    def __init__(self, button):
        self.button = button    # save the button reference    

    # called when a radiobutton is selected
    def choiceClick(self):
        self.button['state']=NORMAL # enable the button

So, how do we go about connecting up this Mediator? We create the button and then create the Mediator, passing it a reference to that button:

playButton = Button(root, text="Play", command=self.playgame)
playButton.grid(row=3, column=0, pady=20)
playButton['state'] = DISABLED
med = Mediator(playButton)     # create the Mediator 

So, now the Mediator knows about the button. What about the radio buttons? You may recall that we have derived a ChoiceButton class so it can contain the gvar variable. All we need to do is pass the mediator reference to each button as we create it:

ChoiceButton(lbf, "Paper", 0, med).grid(row=0, column=0, sticky=W)
ChoiceButton(lbf, "Rock", 1, med).grid(row=1, column=0, sticky=W)
ChoiceButton(lbf, "Scissors", 2, med).grid(row=2, column=0, sticky=W)

And the ChoiceButtpm itself creates a command that calls choiceClick in the Mediator:

class ChoiceButton(Radiobutton):
    gvar = None
    def __init__(self, rt, label, index, med):
        super().__init__(rt, text=label,
                         variable=ChoiceButton.gvar,
                         command=self.comd,
                         value=index)
        self.med = med  # Save the Mediator reference

    def comd(self):
         self.med.choiceClick() #call the Mediator

So anytime a ChoiceButton is clicked, it calls choiceClick and that enables the Play button.

Summary

So, to summarize, we use the Mediator to take care of classes that need to send each other information. In this case, clicks on the radio buttons tell the Mediator to enable the Play button. Before that it is disabled. In general, the Mediator is an excellent solution when two or more classes need to tell each other about click events and the like and prevents you having to write GUI classes that know about other GUI classes, and thus getting entangled.

Code for this and the previous two articles can be found on GitHub at jameswcooper/articles

Rock, Paper Scissors in Python: Part II,  Building a GUI

Rock, Paper Scissors in Python: Part II, Building a GUI

In our first article, we designed a Rock, Paper, Scissors game that works from the keyboard. It printed out messages and shows the total score when you quit. But even a game this simple will benefit from a graphical user interface (GUI). Here we show how to use the Tkinter toolkit to create that simple interface. Specifically, we are going to use the tkinter.ttk toolkit, because it has a nice LabelFrame widget to hold the three RadioButtons.  It looks like this:

You can select the three possible plays from the radio buttons in the “Plays” LabelFrame, and then click on the Play button to have the program player select its move and tell you who won.  The messages from the program are shown in the Listbox on the right, showing what the Auto player has selected, and who wins. The total score for the two players is shown in the blue label above the Listbox.

Creating the GUI

For simple programs like this, we usually create a Builder class with a build method and a few other methods as needed. Here the only method we’ll need is the playit method, that triggers one round of play.

 Here is the program’s outline:

import tkinter as tk
from random import randint
from tkinter import *
from tkinter.ttk import *

class Builder():
    # play one game
    def playgame(self):
        # players play game

    # create window     
    def build(self):
       root = tk.Tk()
       root.geometry("300x200")
       root.title("Rock paper scissors")
        #UI creation code   
        mainloop()     # start the window

# Program starts here
if __name__== "__main__":
    bld = Builder()
    bld.build()

Adding GUI Controls

We use the Grid layout to arrange the GUI widgets, with the LabelFrame and Play  button in column 0 and the score label and Listbox in column 1. The three radio buttons are inserted into the label frame inside their own three line grid.

The only sneaky part is the way the Radio Buttons work. All of radio buttons in a group use the same variable to tell you which button has been selected. That variable is an IntVar, an integer wrapped in an object that is required by the underlying tk toolkit. So, when you create each Radiobutton, you have to pass it a reference to that IntVal variable, and the value that that button will pass to the IntVar, usually small integers, such 0, 1 and 2.

The design question we have to solve is where that IntVar variable will be located so each of the RadioButtons can access it. The obvious place is right inside the radio button code itself. So we derive a new ChoiceButton from Radiobutton that contains the class level variable gvar. Now all instances of the ChoiceButton have access to that same variable, and can change it to 0, 1 or 2 depending on which button is clicked. Here’s the whole new ChoiceButton class.

class ChoiceButton(Radiobutton):
    gvar = None  # will be set to an IntVar

    def __init__(self, rt, label, index):
        super().__init__(rt, text = label,
                         variable =ChoiceButton.gvar,
                         value=index)
        self.text = label
        self.index=index

When we create the GUI, we will set that gvar to an IntVar. The complete GUI code is

def build(self):
    root = tk.Tk()
    root.geometry("300x200")
    root.title("Rock paper scissors")
    # create a label frame for the radio buttons
    lbf = LabelFrame(root, text="Plays")
    lbf.grid(row=0, column=0, rowspan=3, pady=10, padx=10)
    
# create 3 radio buttons, but set none as selected

    ChoiceButton.gvar = IntVar()
    ChoiceButton.gvar.set(-1)   # none selected
    ChoiceButton(lbf, "Paper", 0).grid(row=0, column=0, sticky=W)
    ChoiceButton(lbf,"Rock", 1).grid(row=1, column=0,sticky=W)
    ChoiceButton(lbf, "Scissors", 2).grid(row=2,column=0, sticky=W)

    # create Play button - calls playgame method
    playButton = Button(root,text="Play", command=self.playgame)
    playButton.grid(row=3,column=0,pady=20)

    # create score label
    self.scoreLabel = Label(text="scores", foreground="blue")
    self.scoreLabel.grid(row=0, column=1)

    # create listbox
    self.mesgList = Listbox(root, width=30)
    self.mesgList.grid(row=1, column=1, rowspan=3)

    # create two players
    self.player1 = Player("You")
    self.player2 = AutoPlayer("Auto", self.mesgList)
    mainloop()

Note that we use the same Player and AutoPlayer classes as in the previous example;. The only difference is that the AutoPlayer adds a message to the Listbox instead of printing it on the console:

class AutoPlayer(Player):
    def __init__(self, name, list):
        super().__init__(name)
        self.list = list

    def playit(self):
        playval = randint(0, 2)
        self.play = Player.moves[playval]
        self.list.insert(END, self.name + " selects " + self.play)
        self.list.yview(END)

The Player class differs only in its playit method, which obtains the selected Radiobutton from the index in gvar. Note the yview(END) method on the Listbox, which scrolls to the bottom of the list so that the last line always shows.

# play one game
def playit(self):
    playval = ChoiceButton.gvar.get()
    index  = int(ChoiceButton.gvar.get())
    self.play = Player.moves[index]

And the playGame method of the Builder class differs only in that the winner is added to the Listbox, and the label is updated to show the current score:

def playgame(self):
   self.player1.playit()    # read buttons
   self.player2.playit()    # calc random play  
# compute winner
   winner = Winner(self.player1, self.player2)
   self.mesgList.insert(END, winner.findWin())  # print winner
   self.mesgList.yview(END) #move to bottom of list 
# show current score
   self.scoreLabel.config(text="You: "
                            +str(self.player1.wincount)+"--- Auto: "
                            +str(self.player2.wincount))

Conclusion

The differences in the console game and the GUI version are pretty small. The Player class gets your play from the radio button selected, and all the messages are added to the Listbox. The running score is changed in the scoreLabel each time.

All of the code for this example can be found in Github at jameswcooper/articles/rockpaper

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.