tkinter canvas not updating color

后端 未结 2 1923
一向
一向 2021-01-24 20:35

I draw an oval into a canvas which works perfect also it show color red and the loops runs fine too cause I can see the print. Its supposed to change the color ever 1000ms. But

2条回答
  •  孤城傲影
    2021-01-24 20:58

    The problem you are having is that you are creating the canvas on every iteration, and packing it below all of the other canvases. When you say the object color isn't changing, that's because you are observing the first canvas you created; the color is changing for the most recently created canvas but it is off screen.

    Change your code to create a single canvas and your code will otherwise work just fine. For example:

    import Tkinter as tk
    
    class App(tk.Tk):
        def __init__(self):
            tk.Tk.__init__(self)
            self.frame_Light = tk.Frame(self, background="bisque")
            self.frame_Light.pack(side="top", fill="both", expand=True)
            self.light_on = True
            self.canvas = tk.Canvas(self.frame_Light)
            self.canvas.create_oval(10, 10, 30, 30, fill="yellow", tags="light")
            self.canvas.pack(side="top", fill="both", expand=True)
            self.draw_light()
    
        def draw_light(self):
    
            if self.light_on:
                self.canvas.itemconfig("light", fill="blue")
                self.light_on = False
                print "on"
            else:
                self.canvas.itemconfig("light", fill="red")
                self.light_on = True
                print "of"
    
            self.after(1000, self.draw_light)
    
    app = App()
    app.mainloop()
    

提交回复
热议问题