I am a newbie at coding and Python. Still, I enjoy every new thing I
Am working through my third beginner’s book now. Everything works well when I type in the practice codes and I also get a better understanding why code works as they do.
Until I get to the tkinter chapters…
This is the third time now that I can’t get anything to work, even when I replicate it exactly as it is in the books. I thought trying from a different book might help me see something I missed, but clearly that’s not working.
I looked around a little and by adding tk.mainloop() I finally got things to work in the easiest assignments, but it’s strange to me that the books don’t mention this ‘mainloop’.
I suspect they do. Somewhere. It is critical. But maybe they have
omitted it from the examples for simplicity.
Did more people experience this, or am I making some common beginner’s
I expect everyone experiences it at least once when starting to write
GUIs - they almost all work this way.
A GUI is often structured as:
- set up the widgets
- run a loop to process their activity (the mainloop)
This is because unlike your typical small procedural programme where you
do some setup, and then do some stuff until it is done, a GUI lays out
some things on the screen and then acts in response to user activity.
Because the user might do anything with the widgets displayed in any
order there’s no predefined sequence of things to do, just user actions
and things to do when those occur.
So after the setup there needs to be a process which listens to the GUI
and acts on iteraction. Because there are many many possible things
which might cause activity (even moving the mouse pointer over a
widget), your setup generally goes:
- define some widgets
- specify a few particular things to respond to (eg a button click)
Then the main loop listens to all events, and when the interesting
ones you’d specified occur, calls your handler forthe event. The others
are ignored (well, some have automatic presupplied responses too, like
things with changes colour when they get the focus, etc).
MOst GUI libraries therefore preprovide a “mainloop” function of some
kind whose entire purpose is to sit listening for events and to act on
them. You need to call that to make the GUI function, after all the
setup. Otherwise nothing is listening to events and nothing happens.
Probably your programme reaches the end and quits, instantly.
You may have written the common “prompt for an input and do something”
loop whe learning Python, or other languages. Something like this made
entries = 
answer = input("Enter something, or 'quit' to quit: ")
if answer == 'quit':
print("You entered these things:", entries)
That is a mainloop for an interactive terminal: wait for an event
(input()), do something in response. The tkinter mainloop is a more
elaborate one, watching for GUI events instead of keyboard input.
Cameron Simpson firstname.lastname@example.org