How to update colour variable outside of the function and update the window/canvas? (tkinter)

Question:

So I’m trying to create this pokeball designer. I’ve created a colour variable which is set to ‘red’ at the start, then there is a button which assigns green to the colour variable though it doesn’t seem to update it outside the function and it doesn’t update the colour of the shape in the window.

So how would I update the colour variable outside the window?

And how would I get it to update on the canvas?

from tkinter import *

width = 500  # size of window is set
height = 500

colour = 'red'  # colour is initially set to red


def colourchange():
    colour = 'green'
    window.update()


window = Tk()  # creates window
canvas = Canvas(window, width=width, height=height)  # creates canvas
canvas.create_arc(10, 10, width - 10, height - 10, fill=colour, style=PIESLICE, extent=180, width=10)  # creates top shell of pokeball
canvas.create_arc(10, 10, width - 10, height - 10, fill='white', style=PIESLICE, extent=180, width=10, start=180) # creates bottom shell of pokeball

colourButton = Button(window, text='Switch Colour', command=colourchange) # creates button to switch colour of pokeball
colourButton.pack() 

canvas.pack()
window.mainloop()
Asked By: Jackalope786

||

Answers:

If you want to change the color then you need to configure it like you did when you created it. You do not need to use the update() method here. You can do something like this.

from tkinter import *

width = 500  # size of window is set
height = 500

colour = 'red'  # colour is initially set to red


def colourchange():
    colour = 'green'
    canvas.create_arc(10, 10, width - 10, height - 10, fill=colour, style=PIESLICE, extent=180, width=10)


window = Tk()  # creates window
canvas = Canvas(window, width=width, height=height)  # creates canvas
canvas.create_arc(10, 10, width - 10, height - 10, fill=colour, style=PIESLICE, extent=180, width=10)  # creates top shell of pokeball
canvas.create_arc(10, 10, width - 10, height - 10, fill='white', style=PIESLICE, extent=180, width=10, start=180) # creates bottom shell of pokeball

colourButton = Button(window, text='Switch Colour', command=colourchange) # creates button to switch colour of pokeball
colourButton.pack() 

canvas.pack()
window.mainloop()
Answered By: Rory

You cannot change global variable colour in a fuction this way. Your code creates a new local variable colour inside the function. If you want to change the colour using the function then add the global keyword

def colourchange():
    global colour
    colour = 'green'
    window.update()
Answered By: Vivek Singh
def colourchange():
    global colour
    colour = 'green'
    window.update()

you need to use global keyword to access the outside variable

Answered By: Shreyash Pandey