28
Learning to Program With Python Beginners’ Class 9

Beginners’ Class 9. Topics GUI programming with Tkinter

Embed Size (px)

Citation preview

Learning to ProgramWith Python

Beginners’ Class 9

Topics

GUI programming with Tkinter

A note in advance

A GUI is a “graphical user interface”, which is what you as a user are used to using for virtually every piece of software you’ve ever touched. Every app, every program, every operating system, has a GUI.

The alternative is a text interface, which is what the command line and shell are. IDLE is a mix, a shell wrapped in a GUI.

Text interfacesOld operating systems from decades ago were

entirely text based….there was no mouse , only the keyboard, because there was nothing to click on.

This is back when only programmers and computer scientists had computers, before Apple and Microsoft popularized the graphical user interface and brought personal computers to the masses.

Most people aren’t too good with text interfaces

By the way

GUI is pronounced “gooey”, always.

Never say “gee you eye”. People will look at you strangely.

About GUI programming

Another misconception of beginning programmers (one I held myself) is that the early tasks-- involving mere manipulation of data and text input/output in the shell-- are not real programming, because if they were writing a real program then there would be a GUI with buttons and images and all that stuff.

WRONG.

About GUI programming

Most programs are like icebergs– 90% of their mass is hidden from the uneducated eye. Users see only the GUI, because that’s all they need to see.

The manipulation of data and logic is nearly always the bulk of a program. The GUI is just a skin over the muscles and organs.

About GUI programmingThat’s not to say GUI programming can’t become

incredibly complex, but in general it’s not. It’s easier than manipulating data because it’s easy to visualize exactly what you want the code to do, so you have a clearer idea of what you’re aiming for.

Most GUI programming is done with pre-written libraries that do most of the work for you. You need only call a few functions and methods and do a little custom configuration and bingo, you have a GUI.

GUIs: already done for you.

Sure, giant corporations like Microsoft and Apple have the time and resources to build out graphics libraries from scratch. That requires very knowledgeable and skilled people working full-time in focused teams.

The vast majority of software development entities simply use pre-existing GUI libraries. Why not?

Tk / tkinter

Tk is one such graphical library. It was originally written for a now somewhat uncommon programming language called Tcl (“tickle”), but has been ported over to many other languages.

tkinter is like an expansion to that library, which adds compatibility for the different looks of the different modern operating systems.

Tk / tkinterTk/tkinter is Python’s standard GUI library….it’s

part of the Standard Library. It comes pre-installed with python. IDLE has a tkinter GUI.

There are many other graphical libraries for python, some of which are far more powerful and complex, and some of which are even simpler and more basic. But I think tk is pretty great for getting started, until the day comes when you find yourself trying to do something that tk is apparently incapable of.

Final intro note

If you haven’t attended the advanced class, you’re going to see some syntax that’s maybe just a little bit mysterious. That’s ok.

Programmers routinely use things they don’t understand completely, but which work. As you continue learning and writing code, things will become progressively more and more clear.

Getting started#this is the standard setup for importing tk/tkinterfrom tkinter import *from tkinter import ttk

#creates a blank window, whose name in the code is rootroot = Tk()#sets the window’s title (the name at the top)root.title(“Clock”)#activates the window so it becomes ‘live’ and usableroot.mainloop()

Side noteIf you write the code from the previous slide in an

IDLE editor window and hit F5, it’ll run fine, and you’ll see a blank window.

If you try double-clicking the saved file to run it just using Python, no IDLE involved, (on Windows) you’ll see your blank window and a black console.

To hide that console (on Windows), save your script as a .pyw instead of a .py. This signifies to python: “GUI application, do not display the console.”

Keeping it simple

What we’re going to write is quite simple: just a digital clock. No input, only output. A good starting point.

The GUI equivalent of “Hello World!”

Notes: StringVarThe StringVar we use to hold our time is tkinter’s

special version of a simple primitive string.

It has some special properties tied into tk/tkinter. It has nothing to do with anything outside of tk/tkinter.

It is created like this:myStringName = StringVar()myStringName.set(“intended value for the

string!”)

Notes: StringVar

Correspondingly, there is BooleanVar, IntVar, and DoubleVar (the equivalent of a float).

For all of them, the .set() method is used to update their value.

Again, all of these are only for tk/tkinter programming.

Notes: LabelA Label is just one kind of “widget” in the tkinter library.

There are many others, such as Buttons, Canvases, Entries (for entering text), RadioButtons, and so on.

A Label simply displays some text, such as our clock.

The Label is tied to the time_display StringVar, which is where the special properties of the StringVar come in– when the StringVar’s value changes, the Label immediately updates to reflect that change. That would not work with an ordinary string.

Notes: creating the Label

The line in which the Label is created contains a lot of stuff. The first argument, root, is telling the Label creator to place this Label inside our root window.

After that we see some unfamiliar syntax which goes by the name of “keyword arguments”. Keyword arguments let us specify which arguments we want to pass in, since some functions have optional arguments.

Notes: creating the Label

So we specify that the ‘textvariable’ argument should be given the value ‘time_display’. The textvariable is the StringVar that the Label needs to watch for changes, so that when the StringVar’s value changes, the Label updates accordingly.

The font argument should be reasonably self-explanatory….we pass a tuple (similar to a list) of details as to the font specifications. 300 is the size.

Notes: creating the LabelThe ‘background’ and ‘foreground’ of course dictate the

colors of the label.

After that we use the .grid method to tell the Label where it should go inside the root window--- inside the 0th column and 0th row of the grid you cannot see and which we have not discussed.

The grid is how you arrange things when you have multiple elements in your UI. We only have one element, a Label, so this is simple. There are no other columns or rows here.

Notes: .after method

Here we use the .after() method to tell the window (root) to call the function updateTime() after an interval of 500 milliseconds with the argument ‘var’, which is pointing to the time_display StringVar.

The updateTime function is infinitely recursive, so it will continually be called every half a second, so our time never stops updating. Which is what we want.

Closing notesAs initially noted, this was only intended to be a very

basic introduction to GUI programming– a “Hello World!” of sorts.

To learn to create even an alarm clock with inputs and outputs would require significantly more time, far more than we have in the space of <50 slides, assuming I actually continued giving good explanations.

But it’s very manageable on your own.

Closing notes

If you want to try to make a GUI for your programs, read some tutorials. Read references. Read other people’s code examples. There’s a lot of really good information for tkinter in Python.

There’ll be a learning curve, especially with the grid layout system for positioning elements inside a window, but it’s not too bad.

Closing notes

If you keep at it, months or years from now you will find yourself wanting to make a GUI with features that tk/tkinter simply can’t provide, at which time you can think of yourself as having graduated from tkinter GUIs.

There are many other GUI libraries out there, some of which are huge. Qt is one such massive industry standard.

Closing notesRemember, if you ever want a truly custom

interface, like the main menus in video games, that’s where programs like PhotoShop and Illustrator come in. You literally have to make the graphics yourself!

But then you can use a graphics library to load those graphics up and make them behave like a menu interface. A picture is just a picture until some line of code tells it that is in fact now a button with a click event tied to it.

The End

The first time I ever saw a peer write a program, I was a freshman in high school and he had made a digital alarm clock not so much different from what we just wrote.

That was 9 years ago. I didn’t start writing code myself until 4 years ago. You can come a long way in a short time if you want to.

The EndI hope this set of beginner slides has helped to

acquaint some people with Python and helped them to see how fun (albeit frustrating) programming can be.

These slides are far from perfect….there’s a lot of restructuring I would like to do in the future.

But from here, for now, the slides from the corresponding Advanced Class might be a good place to continue learning.