调用类的方法以更改python类的位置的最佳方法

调用类的方法以更改python类的位置的最佳方法,python,class,methods,tkinter,Python,Class,Methods,Tkinter,我有下面的代码,试图在不同的位置创建另外两个不同颜色的Ball类实例。目前,创建椭圆并指定其位置的方法是init方法 问题:我曾尝试创建ball2和ball3(创建类Ball的实例),但都没有成功。它们覆盖了ball1,原因很明显 我在寻找一些关于最佳解决方案的建议,并给出答案(代码) 最好直接从现在的位置调用该方法,如果是,如何调用?(我试过各种不起作用的东西) 另外,创建一个新的方法来画球是否更符合python或者更有效,如果是,你能提供一个答案吗 理想情况下,答案应包含上述内容以及解释或任

我有下面的代码,试图在不同的位置创建另外两个不同颜色的Ball类实例。目前,创建椭圆并指定其位置的方法是init方法

问题:我曾尝试创建ball2和ball3(创建类Ball的实例),但都没有成功。它们覆盖了ball1,原因很明显

我在寻找一些关于最佳解决方案的建议,并给出答案(代码)

最好直接从现在的位置调用该方法,如果是,如何调用?(我试过各种不起作用的东西)

另外,创建一个新的方法来画球是否更符合python或者更有效,如果是,你能提供一个答案吗

理想情况下,答案应包含上述内容以及解释或任何其他备选方案(如有)

下面的代码

class Ball: #create a ball class
    def __init__(self,canvas,color): #initiliased with the variables/attributes self, canvas, and color
        self.canvas=canvas #set the intiial values for the starting attributes
        self.id=canvas.create_oval(30,30,50,50,fill=color) #starting default values for the ball
        """ Note: x and y coordinates for top left corner and x and y coordinates for the bottom right corner, and finally the fill colour for the oval
        """
        self.canvas.move(self.id,0,0) #thia moves the oval to the specified location

    def draw(self): #we have created the draw method but it doesn't do anything yet.
        pass 


ball1=Ball(canvas,'green') #here we are creating an object (green ball) of the class Ball

ball2=Ball(canvas,'blue')
ball3=Ball(canvas,'purple')
例如,为了尝试将其移动到一个方法中,我尝试了以下方法,但没有成功:

 def moveball(x_position,y_position):
        self.canvas.move(self.id,0,0)


ball3=Ball(canvas,'purple')
ball3.moveball(100,100)
错误:

    ball3.moveball(100,100)
TypeError: moveball() takes 2 positional arguments but 3 were given
def move(self,x,y): #we have created the draw method but it doesn't do anything yet.
        canvas.move(self.id,x,y)

刚找到这个,确实有用。显然,我们将拭目以待,看是否有人能提出更好或更有效的方案

创建以下方法:

    ball3.moveball(100,100)
TypeError: moveball() takes 2 positional arguments but 3 were given
def move(self,x,y): #we have created the draw method but it doesn't do anything yet.
        canvas.move(self.id,x,y)
像这样称呼ball3:

    ball3.moveball(100,100)
TypeError: moveball() takes 2 positional arguments but 3 were given
def move(self,x,y): #we have created the draw method but it doesn't do anything yet.
        canvas.move(self.id,x,y)
3.移动(100200)


这将根据问题的要求,在另一个位置向屏幕生成另一个球

为了防止错误发生,您需要添加
self
作为
moveball
的参数,如果它在您的ball类中。(这必须是第一个论点)

您的球不会相互“覆盖”,它们只是按照您创建它们的顺序在画布上相互覆盖


您可以通过在创建后移动它们(指定x和y数量)或通过传递初始坐标(x1、y1、x2、y2或x、y,然后使用偏移量)来防止出现这种情况。

您试图解决的问题到底是什么?请看,我已对问题进行了编辑,以便更清楚地包含问题。balls2和ball3(实例)覆盖ball1。我正在寻找一种最有效的方法来解决这个问题——要么调用init类中的属性,要么修复我创建另一个方法的尝试,但这不起作用(请参见编辑)