Hello,
I am working on a Tk program that generates geometric patterns, and I have written into all of my defs that if the variable "outline" is True it will draw a black outline, otherwise it will draw an outline the same as the fill.

I tried a function called toggle:

outline = True # when the program starts

def toggle(dummy): #dummy is just to get the event from the bind, it isn't used.
    if outline == True:
        outline = False
    if outline == False:
        outline = True

with a bind at the end:

root.bind("k", toggle)

this doesn't work because according to the function, the variable "outline" hasn't been declared because the function can't access it or something.
How can I make it so that the function can change the value of outline? I don't have any classes in my program.

Thanks in advance,
Joe

There are different ways. 1: declare outline global inside the function

outline = True # when the program starts

def toggle(*args): # args ignored
    global outline # at the top of the function
    if outline == True:
        outline = False
    if outline == False:
        outline = True

2: use a class to hold global variables (avoid global statement)

class glo:
    outline = True # when the program starts

def toggle(*args):
    glo.outline = not glo.outline

3: use a module to hold global variables (especially useful is your program uses more than one file)

# in file glo.py
outline = True

# in your main program
import glo

def toggle(*args):
    glo.outline = not glo.outline

3: Create a class to hold global variables and function and use a single instance

class MyApp:
    def __init__(self):
        self.outline = True

    def toggle(self, *args):
        self.outline = not self.outline

if __name__ == '__main__':
    my_app = MyApp()
    # ...
    Button(..., command = my_app.toggle)
    #...
    foo.mainloop()

4: etc

Edited 3 Years Ago by Gribouillis

More modern:

''' 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 question has already been answered. Start a new discussion instead.