Lecture 38

GUIs with tkinter 2

MCS 260 Fall 2021
David Dumas

Reminders

  • Homework 13 due Tue 10am
  • No labs next week. TA office hours instead.
  • If Proj 4 proposal not yet approved, revise and resubmit by Tue Nov 23.

Goal

Build a more interesting tkinter GUI application.

We'll make a password generator.

Subclassing Tk

A good way to make GUI applications is to subclass tkinter.Tk and put GUI setup code in __init__.

Then, application data can be stored as class attributes.

Commands and other callbacks can be methods.

rowspan and columnspan

These options for .grid of a widget make it span multiple columns or rows in the layout.

tkinter variables

tkinter offers mutable variable classes designed to work with widgets:

  • tkinter.StringVar — mutable string
  • tkinter.DoubleVar — mutable float
  • tkinter.IntVar — mutable integer

All use .set(val) to set, .get() to get. They automatically notify widgets that use them of changes.

Variable change callbacks

tkinter variables let us register a function to be called whenver the value changes:

tkvar.trace_add("write",callback)

The function callback is called with three arguments (internal name, internal index, operation). Usually you want to ignore all of these arguments.

References

Revision history

  • 2021-11-19 Initial publication