How do I make an object move on the screen using Tkinter?

Asked

Viewed 780 times

0

I’ve already started my code only I don’t know what’s going wrong so that my object doesn’t 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()

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 Bola. Thus,

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

    You should save the object as a class object:

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

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

    Should stay:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.