A simple way to create a toggle button for the Tkinter Python GUI toolkit.

# use config() to create a Tkinter toggle button

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def toggle():
    '''
    use
    t_btn.config('text')[-1]
    to get the present state of the toggle button
    '''
    if t_btn.config('text')[-1] == 'True':
        t_btn.config(text='False')
    else:
        t_btn.config(text='True')

root = tk.Tk()

t_btn = tk.Button(text="True", width=12, command=toggle)
t_btn.pack(pady=5)

root.mainloop()

Nice approach! Here is another option to do this ...

''' tk_button_toggle2.py
use a list default argument to create a Tkinter toggle button
'''

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def toggle(tog=[0]):
    '''
    a list default argument has a fixed address
    '''
    tog[0] = not tog[0]
    if tog[0]:
        t_btn.config(text='False')
    else:
        t_btn.config(text='True')

root = tk.Tk()

t_btn = tk.Button(text="True", width=12, command=toggle)
t_btn.pack(pady=5)

root.mainloop()
Comments
Good stuff.

So we are spending our time on simple toggles huh. This uses a list so the function has access to the previous setting. I was too lazy to create a class with an instance variable.

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def toggle():
    index_dict={"True": "False", "False": "True"}
    index[0] = index_dict[index[0]]
    t_btn['text'] = index[0]

root = tk.Tk()
index=["True"]
t_btn = tk.Button(text=index[0], width=12, command=toggle)
t_btn.pack(pady=5)

root.mainloop()

Edited 3 Years Ago by woooee

Just one more ...

''' tk_button_toggle4.py
using itertools.cycle() to create a Tkinter toggle button
'''

import itertools
try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk


def toggle():
    #global icycle
    # works with Python27 and Python3
    state = next(icycle)
    t_btn['text'] = str(state)

root = tk.Tk()
icycle = itertools.cycle([False, True])
t_btn = tk.Button(text="True", width=12, command=toggle)
t_btn.pack(pady=5)

root.mainloop()

Edited 3 Years Ago by vegaseat

This deserves an answer:

''' tk_button_toggle5.py
'''

from functools import partial
import itertools
import sys
python2 = sys.version_info[0] == 2
tk = __import__("tT"[python2] + "kinter")

def toggle(button):
    button.state = not button.state
    button['text'] = str(button.state)

def new_btn(state):
    btn = tk.Button(width=12)
    btn.state = bool(state)
    btn.config(text= str(btn.state), command = partial(toggle, btn))
    btn.pack(pady=5)
    return btn    

root = tk.Tk()
for x in (1, 0, 1):
    new_btn(x)

root.mainloop()

Notice that btn.state can now be accessed directly.

Edited 3 Years Ago by Gribouillis

Vegaseat's code more elegant:

''' tk_button_toggle6.py
using itertools.cycle() to create a Tkinter toggle button
'''

import itertools
try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk


def toggle(icycle=itertools.cycle([False, True])):
    state = next(icycle)
    t_btn['text'] = str(state)

root = tk.Tk()

t_btn = tk.Button(text="True", width=12, command=toggle)
t_btn.pack(pady=5)

root.mainloop()

This can be accomplised in one line using "lambda" and a one line "if/else" statement:

t_btn = tk.Button(root, text="True", width=12, command = lambda: t_btn.config(text="False") if t_btn.config('text')[-1] == 'True' else t_btn.config(text="True"))

Edited 1 Year Ago by BustACode: Change code.

You can do it with images as well:

    from Tkinter import *
    root=Tk()
    c=Button(root,justify = LEFT, command = lambda: c.config(text="False", image = io_LEDRedOff) if c.config('text')[-1] == 'True' else c.config(text="True", image = io_LEDRedOn))
    io_LEDRedOn=PhotoImage(file="LED-Red-On.gif")
    io_LEDRedOff=PhotoImage(file="LED-Red-Off.gif")
    c.config(text = "False", image=io_LEDRedOff, width="15",height="15")
    c.pack(side=RIGHT)

    root.mainloop()

NOTE: Images in code are here: http://i.imgur.com/uMzb0g9.gif
http://i.imgur.com/bFo9AtY.gif

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.