How do I move an object on the screen using tkinter?

0

I have already started my code, I just do not know what is going wrong so that my object does not move

#Praticar movimentação de objetos
from tkinter import*

class Bola(object):
    def __init__(self):
        self.janela = Tk()
        self.janela.geometry('600x500')
        self.janela.title ('Bola')
        self.janela.resizable(False,False)

        self.frame = Frame(bg='blue')
        self.frame.pack()

        self.canvas = Canvas(self.frame, bg='blue', width=400, height=400, cursor='target')
        self.canvas.pack()

        raio = 29
        p = (100,200)
        self.canvas.create_oval(p[0],p[1],p[0]+raio,p[1]+raio, fill='grey' )
        self.vx = self.vy = 3
        self.x, self.y = p

        self.iniciar = Button(self.janela, text='INICIAR', command=self.comecar)
        self.iniciar.pack()
        self.janela.mainloop()

    def comecar(self):
        self.jogar()

    def jogar(self):

        self.update()
        self.janela.after(1, 10)

    def update(self):
        self.canvas.move('bolinha' , self.vx ,self.vy)
        self.x += self.vx
        self.y += self.vy


if __name__ == '__main__':
     Bola()
    
asked by anonymous 23.04.2018 / 01:15

1 answer

0

Your code has three problems:

  • It does not call the play function repeatedly because it is not passed to after .

    def jogar(self):
    
        self.update()
        self.janela.after(1, 10)
    

    Should be:

    def jogar(self):
    
    self.update()
    self.janela.after(1, self.jogar)
    
  • bolinha must be stored in the instance of Bola . Thus,

    self.canvas.create_oval(p[0],p[1],p[0]+raio,p[1]+raio, fill='grey' )
    

    You should save the object as an object of the class:

    self.bolinha = self.canvas.create_oval(p[0], p[1], p[0] + raio, p[1] + raio, fill='grey')
    
  • The move function must be called with the object to be moved as the first argument. Thus,

    self.canvas.move('bolinha' , self.vx ,self.vy)
    

    Should be:

    self.canvas.move(self.bolinha, self.vx ,self.vy)
    
23.04.2018 / 02:17