我有一个运行多个函数的类。其中之一是在屏幕上绘制一个物体。我有另一个函数可以更新对象的状态,并且根据修改后的状态,我必须更改对象的颜色。如何在更新状态的函数内调用绘制形状的函数。代码如下所示:
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
当通过 update_state()
修改状态时,我需要运行 draw()
。
最佳答案
self
它是当前实例,因此您可以调用它的每个方法并访问每个属性。
因此您只需调用:
self.draw()
所以代码变成:
def update_state(self, state):
self.state = state
self.draw()
关于Python-在类函数内调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60039397/