1

I want to update the color of a circle in Tkinter in python 2. I can make my circle but the color does not update in my task() method until I stop running the program. How can I make the color update as soon as val is greater than 4?

from Tkinter import *
m = Tk()
w = Canvas(m, width = 100, height = 100)
w.pack()
cir = w.create_oval(50, 50, 100, 100)

def task():
    while True:
        val += 1
        if val > 4:
            w.itemconfig(cir, fill = "blue")

m.after(2000, task)
m.mainloop()
6
  • 1
    You have a while True: with no break. What did you expect? Commented Jul 20, 2015 at 21:36
  • I wrote the code wrong the first time but even with this fix it still doesnt update color Commented Jul 20, 2015 at 21:50
  • You still have a while True: with no break. Again, what did you expect? Commented Jul 20, 2015 at 21:55
  • @Brosten Please don't ninja-edit your question -- by adding indentation after people were already helping, you changed the code and rendered existing feedback redundant at best, and confusing at worst. Commented Jul 20, 2015 at 22:02
  • Given the code change, I'm removing my answer. Note that the problem lies in what @TigerhawkT3 identified in comments on that answer -- namely, you're hogging an entire CPU core to increment val as fast as it can, basically freezing your program unless you go into multiprocessing/threading. What you're trying to ask is how to refresh the display between each while True cycle. Commented Jul 20, 2015 at 22:07

2 Answers 2

1

This will work.

Like @TigerhawkT3 said you need a break to exit the loop.

from Tkinter import *
m = Tk()
w = Canvas(m, width = 100, height = 100)
w.pack()
cir = w.create_oval(50, 50, 100, 100)

def task():
    val = 1
    while True:
        val += 1
        if val > 4:
            w.itemconfig(cir, fill = "blue")

            #without the break task will run forever
            break

m.after(2000, task)
m.mainloop()
Sign up to request clarification or add additional context in comments.

1 Comment

The OP commented in a now-deleted answer that he wants to keep incrementing val even after changing the fill color (didn't explain why, though).
0

I'm afraid you'll have to do it the long way, and the only way. Code:

from tkinter import *

m = Tk()

c = Canvas(root, width=100, height=100)
c.pack()

v = 4

if v == 4:
    v = 0
    c.pack_forget()
    del c

    c = Canvas(root, width=100, height=100, bg='blue')
    c.pack()

c.mainloop()

Do all the changing with v (I haven't put that in though)! Hope this helps!

1 Comment

Wait, I didn't mean v, I meant val, sorry!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.