Hi,

I want to create a toggle button, i.e., a button that when clicked goes
down (if it is up) and goes up (if it is down).

One easy way to achieve this is to set the button's style to
"Toolbutton" (see self.toggle2). But unfortunately, that gets rid of the
button's relief so it looks out of place amongst other non-toggling
buttons.

I solved if for Linux using a custom style (see self.toggle3). But this
doesn't work on Windows and I can't figure out how to solve it.

Can anyone suggest a solution?

Here's the code I've got:

############################################################
import tkinter.ttk

class Window(tkinter.ttk.Frame):

    def __init__(self, master=None):
        super().__init__(master)
        self.toggle1 = tkinter.ttk.Button(text="Off",
                command=lambda *args: self.toggle(self.toggle1))
        self.toggle1.pack(padx=5, pady=5)
        self.toggle2 = tkinter.ttk.Button(text="Off", style="Toolbutton",
                command=lambda *args: self.toggle(self.toggle2))
        self.toggle2.pack(padx=5, pady=5)
        self.toggle3 = tkinter.ttk.Button(text="Off", 
                command=lambda *args: self.toggle(self.toggle3))
        self.toggle3.pack(padx=5, pady=5)
        style = tkinter.ttk.Style()
        style.configure("Toggle.TButton")
        style.map("Toggle.TButton", relief=[("pressed", "sunken"),
            ("selected", "sunken"), ("!selected", "raised")])
        self.toggle3.config(style="Toggle.TButton")
        tkinter.ttk.Button(text="Quit",
                command=self.master.destroy).pack(padx=5, pady=5)
        self.pack()

    def toggle(self, button):
        if button.instate(("!selected",)):
            button.state(("selected",))
            button.config(text="On")
        else:
            button.state(("!selected",))
            button.config(text="Off")


window = Window()
window.master.title("Toggle")
window.master.mainloop()
############################################################

Thanks!

-- 
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
    C++, Python, Qt, PyQt - training and consultancy
        "Programming in Python 3" - ISBN 0321680561
            http://www.qtrac.eu/py3book.html
_______________________________________________
Tkinter-discuss mailing list
Tkinter-discuss@python.org
http://mail.python.org/mailman/listinfo/tkinter-discuss

Reply via email to