bogdanserban
bogdanserban

Reputation: 31

Python - call function inside class function

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().

Upvotes: 3

Views: 3119

Answers (3)

Al Martins
Al Martins

Reputation: 436

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

Upvotes: 0

chin8628
chin8628

Reputation: 476

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(....)

Upvotes: 1

Tommaso Fontana
Tommaso Fontana

Reputation: 730

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()

Upvotes: 3

Related Questions