3

I have a class that runs multiple functions. One of them is drawing an object on the sceen. I have another function that updates the state of the object, and based on the modified state, I have to change the color of the object. How can I call the function that draws the shape inside the function that updates the state. The code looks like this:

 class TrackCircuit:
     def __init__(self, id, name, state):
         self.id = id
         self.name = name
         self.state = state

     def draw(self, pos_x, pos_y, pos_end):
         self.pos_x = pos_x
         self.pos_y = pos_y
         self.pos_end = pos_end
         label_root_x = (pos_x + pos_end) / 2
         label_root_y = offset_top + offset_label
         global tc_width

         if self.state == "undefined":
             tc_color = color_undefined
         elif self.state == "occupied":
             tc_color = color_occupied

         canvas.create_line(pos_x, pos_y, pos_end, pos_y, width=tc_width, fill=tc_color)
         tc_label = Label(root, text="121", font = label_font, bg = label_background, fg = label_color)
         tc_label.place(x=label_root_x, y=label_root_y, anchor=CENTER)

     def update_state(self, state):
         self.state = state

I need to run draw() when state is modified through update_state().

3
  • So you want to call self.draw() inside update_state? Commented Feb 3, 2020 at 12:40
  • 1
    You have to use the self parameter, which refers on the object. By calling self.ANY_METHOD() you call the method ANY_METHOD. So in your case you have to use self.draw() inside of the update_state method. Commented Feb 3, 2020 at 12:41
  • Do you mean call it inside update_state ? Call it as you would normally, self.draw() Commented Feb 3, 2020 at 12:42

3 Answers 3

3

self it's the current instance, so you can call on it every method and access every attributes.

Therefore you simply need to call:

self.draw()

So the code becames:

def update_state(self, state):
    self.state = state
    self.draw()
Sign up to request clarification or add additional context in comments.

Comments

1

You can call a method of the class via self like this:

class TrackCircuit:
    def __init__(self, id, name, state):
        # your code

    def draw(self, pos_x, pos_y, pos_end):
        # your code

    def update_state(self, state):
        self.state = state
        self.draw(....)

Comments

0

If you need a function to dinamically assign choices in an selectfield of WTForm you must do that outside the Class. Find out on Dynamically assign choices in an selectfield of WTForm using a FieldList

Comments

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.