We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,453 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Simple Tkinter Toggle Button

1
By HiHe on Aug 2nd, 2012 4:04 pm

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()
vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 36

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()
woooee
Posting Maven
2,707 posts since Dec 2006
Reputation Points: 827
Solved Threads: 780
Skill Endorsements: 9

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()
vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 36

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.

Gribouillis
Posting Maven
Moderator
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11

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()
Lardmeister
Posting Virtuoso
1,939 posts since Mar 2007
Reputation Points: 465
Solved Threads: 72
Skill Endorsements: 5

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0769 seconds using 2.89MB