简体   繁体   中英

Tkinter Canvas will not update color change via itemconfig

I am working on a project which deals with a kind of a map which has some lines as paths. These paths can have two states, active and inactive with different colors. There is a method which should change the fill-color. I can't figure out why my canvas lines won't update. Here's my simplified code:

import Tkinter

inactive = "#385c61"
active = "#7dd5cd"

map = Tkinter.Canvas()

class GuiPart(object):

    def __init__(self, master):
        #some code

    def initGui(self, master):
        map = Tkinter.Canvas(left, width=660, height=600, bg="#35424b", bd="0", highlightthickness="0")
        map.pack()
        global inactive, active
        pathA = map.create_line(135, c, 135, e, fill=inactive, width=w)

    def setActivePath(self):
        global active, inactive
        map.itemconfig(pathA, fill=active)
        map.update_idletasks()
        map.update()

root = Tkinter.Tk()
gui = GuiPart(root)
gui.initGui(root)

gui.setActivePath()

root.mainloop()

If I change the color with itemconfig inside initGui it works like it should, but later I have to call setActivePath from another class, so it has to be a own method. (I know I call map = Tkinter.Canvas(...) twice, but otherwise I get an error, have to fix that too)

Any ideas?

You need to make map and pathA attributes of the class so that setActivePath can reference it. This is why you were getting the error where you had to create two canvases.

import Tkinter

inactive = "#385c61"
active = "#7dd5cd"

class GuiPart(object):

    def __init__(self, master):       
        #some code

    def initGui(self, master):                     
        self.map = Tkinter.Canvas(left, width=660, height=600, bg="#35424b", bd="0", highlightthickness="0")
        self.map.pack()    
        global inactive, active
        self.pathA = map.create_line(135, c, 135, e, fill=inactive, width=w)

    def setActivePath(self):
        global active, inactive
        self.map.itemconfig(self.pathA, fill=active)
        self.map.update_idletasks()
        self.map.update()

root = Tkinter.Tk()
gui = GuiPart(root)            
gui.initGui(root)

gui.setActivePath()

root.mainloop()

Everything else looks OK to me, though you are saying that this has not resolved your issue. As far as I can see, self.map.itemconfig(self.pathA, fill=active) is correct use of this method (see here and here ) so it is possible that your problem is outside of the code you have posted. I can't test the code properly as you have not included the code in the __init__ method and because on the computer I am using at sixth form only Python 3.4.1 is installed. Please edit your question to include the code in the __init__ method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM