Mark Summerfield <list <at> qtrac.plus.com> writes:
>
> 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!
>
Hi ...
Found that setting the ttk.Checkbutton style to 'TButton' forces it to appear
as
themed button; then, on selection, changing it to 'Toolbutton' gives it a
'sunken' appearance. Works ok under Windows 7.
cb1 = ttk.Checkbutton(f, style='Demo.TButton',
image=(self.noletters, 'selected', self.letters),
command=lambda: self._cb_value_changed(cb1))
def _cb_value_changed(self, cb):
# if a checkbutton is selected, use the 'Toolbutton'
# style to make it appear 'sunken'
if 'selected' in cb.state():
cb['style'] = 'Demo.Toolbutton'
else:
cb['style'] = 'Demo.TButton'
_______________________________________________
Tkinter-discuss mailing list
[email protected]
http://mail.python.org/mailman/listinfo/tkinter-discuss