Page 313 -
P. 313
tkinter models
So how do you use models in tkinter?
Imagine you wanted to add delivery options to the program. You could use
radio buttons and do something like this: It's important to EXPLICITLY give
each button a VALUE.
Radiobutton(app, text = "First Class", value = "First Class").pack()
Radiobutton(app, text = "Next Business Day", value = "Next Business Day").pack()
You then need to create a model for the radio buttons to share. In tkinter,
models are called control variables, and control variables that store text
are called StringVars:
A StringVar is just like the IntVar from
Chapter 7, except that it holds a string value.
service = StringVar() This sets the StringVar to the special value
“None" which means “No value."
service.set(None)
Radiobutton(app, text = "First Class", value = "First Class",
variable = service).pack()
Radiobutton(app, text = "Next Business Day", value = "Next Business Day",
variable = service).pack()
This code will now give us a pair of buttons that work together. If you
select one, the other will automatically become deselected:
Click the SECOND option and
the FIRST will be deselected.
And if you ever need to read or change the model value in the code, you just
need to call the StringVar's get() or set() methods:
This returns the current
>>> print(service.get()) value of the model.
"Next Business Day"
>>> service.set("First Class")
This sets the model object
back to “First Class", which will
automatically select the correct
radio button on the screen.
278 Chapter 8