首页 > 解决方案 > Python - 在类函数中调用函数

问题描述

我有一个运行多个功能的类。其中之一是在屏幕上绘制一个对象。我有另一个更新对象状态的函数,根据修改后的状态,我必须更改对象的颜色。如何调用在更新状态的函数内绘制形状的函数。代码如下所示:

 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

draw()当状态被修改时,我需要运行update_state().

标签: python

解决方案


self它是当前实例,因此您可以在每个方法上调用它并访问每个属性。

因此,您只需要调用:

self.draw()

于是代码变成了:

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

推荐阅读