[Tkinter-discuss] Multiple images on a ttk widget?
Michael Lange
klappnase at web.de
Mon Nov 5 21:04:57 CET 2012
Hi John,
On Sun, 4 Nov 2012 15:22:06 -0700 (MST)
"John W. Shipman" <john at nmt.edu> wrote:
> I'm currently attempting to learn the ttk widgets in the process
> of updating our locally written Tkinter reference manual.
>
> However, I am unable to reproduce the behavior described in this
> paragraph from the Python 2.7.3 library reference. This is
> from http://docs.python.org/2.7/library/ttk.html, in the
> section on the ttk.Widget class, the table of "Label Options":
>
> image: Specifies an image to display. This is a list of 1 or
> more elements. The first element is the default image
> name. The rest of the list is a sequence of statespec/value
> pairs as defined by Style.map(), specifying different images
> to use when the widget is in a particular state or a
> combination of states. All images in the list should have the
> same size.
>
> First of all, image names don't work. I was able to get a
> ttk.Label to display an image by using image=t, where t is an
> instance of ImageTk.PhotoImage.
Looks like this paragraph was copy-and-pasted from man ttk_widget, in
tkinter it surely must be a PhotoImage.
>
> For the rest of it, after an hour of trying I was unable to get
> the state-dependent image changing to work. If anyone has a
> working example of this, I would greatly appreciate it!
>From the docs this seemed quite confusing to me either. After some tries
I came up with the following which seems to work:
#########################################
import tkinter
from tkinter import ttk
root = tkinter.Tk()
img1 = tkinter.PhotoImage(file='gnome-netstatus-idle.gif')
img2 = tkinter.PhotoImage(file='gnome-netstatus-txrx.gif')
img3 = tkinter.PhotoImage(file='gnome-netstatus-error.gif')
l = ttk.Label(root,image=(img1, 'selected', img2, 'active', img3))
l.pack(padx=100, pady=100)
def test(event):
if 'selected' in l.state():
l.state(('!selected',))
else:
l.state(('selected',))
def test2(event):
if 'active' in l.state():
l.state(('!active',))
else:
l.state(('active',))
root.bind('<F1>', test)
root.bind('<F2>', test2)
root.mainloop()
#########################################
Apparently the image-list must be of the form (default-image, statespec1,
img1, statespec2, img2...), where statespecs may be strings or sequences
as in this more complex example:
l = ttk.Label(root,image=(img1, ('!active', 'selected'), img2,
('active', '!selected'), img3, ('active', 'selected'), img4))
Best regards
Michael
.-.. .. ...- . .-.. --- -. --. .- -. -.. .--. .-. --- ... .--. . .-.
Youth doesn't excuse everything.
-- Dr. Janice Lester (in Kirk's body), "Turnabout
Intruder", stardate 5928.5.
More information about the Tkinter-discuss
mailing list