2

I have made a simple game to start learning python, you press a button and the color changes. I have tried to execute this but it doesn't change the color, even tho the variable changes. It’s a bit messy, I know, but I’m still learning.

I've cleaned up the code a little bit

from random import randint
from tkinter import *

color_numb = randint(1,3)
status = True
color = "Blue"
root = Tk()

if True:
    if color_numb == 1:
        color = "Blue"
    if color_numb == 2:
        color = "Orange"
    if color_numb == 3:
        color = "Red"
    T = Text(root, height=2, width=30, fg=color)

def ColorC():
    color_numb = randint(1,3)
    if color_numb == 1:
        color = "Blue"
    if color_numb == 2:
        color = "Orange"
    if color_numb == 3:
        color = "Red"
    T.delete(0.0, END)
    T.insert (END, (color))
    print((color_numb), (color))

buttonA = Button(root, text = 'Change the colour!', command=ColorC)
T.pack()
buttonA.pack()
poke
  • 369,085
  • 72
  • 557
  • 602
  • 1
    The local variable `color` inside `ColorC()` is entirely unrelated to the global variable `color`. A `global color` inside that function would make them both refer to the same thing. – jasonharper Aug 06 '18 at 22:29
  • I'll try that, thanks. –  Aug 06 '18 at 22:35
  • Its giving me a invalid syntax on line 6 col 4 because I added global –  Aug 06 '18 at 22:37

1 Answers1

2

The problem with your code is that you are not actually changing the color of your text widget. You are just setting the color once:

T = Text(root, height=2, width=30, fg=color)

Afterwards, when you click the color, you are attempting to change the color (although you are only modifying the local color variable, not a global one), but you never actually update the text widget’s color.

In order to change the color of the widget, you need to reconfigure it, using configure:

# reconfigure widget color
T.configure(foreground=color)

# delete existing text
T.delete(0.0, END)

# set new text
T.insert(END, color)
poke
  • 369,085
  • 72
  • 557
  • 602