Moving image in python tkinter - python

I am writing a simple program in which I want the (ball image png) to bounce off the walls. So far, I have writen this code:
import tkinter as tk
root = tk.Tk()
WIDTH = 500
HEIGHT = 500
canvas = tk.Canvas(root,bg="white",width=WIDTH,height=HEIGHT)
canvas.pack()
img = tk.PhotoImage(file="images/ball1.png")
ball = canvas.create_image(0,0,anchor="nw",image=img)
yspeed = 2
xspeed = 2
def move_ball():
global xspeed,yspeed,ball
canvas.move(ball,xspeed,yspeed)
canvas.after(10,move_ball)
move_ball()
root.mainloop()

You can get the current position with the coords method, then code in a check for each of the 4 walls. Here's the first one:
def move_ball():
global xspeed,yspeed,ball
xpos, ypos = canvas.coords(ball)
if xpos + width_of_ball > WIDTH:
# ball hit the right edge, reverse x direction
xspeed *= -1
canvas.move(ball,xspeed,yspeed)
canvas.after(10,move_ball)

This answer is the same thing as #Novel answer (even though I wrote it before I saw theirs). The only difference is in the fact that the logic of update doesn't expect you to make any edits for it to work, it considers both horizontal and vertical directions, and resizing the main window is compensated for.
import tkinter as tk
root = tk.Tk()
root.title('Infinite Bounce Simulator')
root.geometry('400x300+300+300')
xspeed = 4
yspeed = 3
canvas = tk.Canvas(root, highlightthickness=0, bg='#111')
canvas.pack(expand=True, fill='both')
ball = canvas.create_oval((0, 0, 20, 20), fill='red')
def update():
global xspeed, yspeed, ball
canvas.move(ball, xspeed, yspeed)
#Left, Top, Right, Bottom coordinates
l, t, r, b = canvas.coords(ball)
#flip speeds when edges are reached
if r > canvas.winfo_width() or l < 0:
xspeed = -xspeed
if b > canvas.winfo_height() or t < 0:
yspeed = -yspeed
#do it all again in 10 milliseconds
root.after(10, update)
root.after_idle(update)
root.mainloop()

Related

Bouncing dvd logo in python tkinter

I am trying to make a bouncing DVD logo in tkinter, but I don't really know how to make it, it works with a ball, the logo doesn't move. The logo
# 1) create main window
from tkinter import *
from PIL import ImageTk, Image
fen = Tk()
fen.title('AllTech - Bouncing ball')
fen.resizable(False, False)
# 2) create canvas and ball
WIDTH, HEIGHT = 400, 300
canvas = Canvas(fen, width=WIDTH, height=HEIGHT)
canvas.pack()
img = ImageTk.PhotoImage(Image.open("dvd.gif"))
# ball = canvas.create_oval(10, 10, 50, 50, fill='black')
# 3) move the ball
xspeed = yspeed = 3
frame = Frame(fen, width=600, height=400)
frame.pack()
frame.place(anchor='center', relx=0.5, rely=0.5)
label = Label(frame, image = img)
label.pack()
def moveBall():
global xspeed, yspeed
canvas.move(canvas, xspeed, yspeed)
(leftPos, topPos, rightPos, bottomPos) = canvas.coords(img)
if leftPos <= 0 or rightPos >= WIDTH:
xspeed = -xspeed
if topPos <= 0 or bottomPos >= HEIGHT:
yspeed = -yspeed
img.after(30, moveBall)
canvas.after(30, moveBall)
fen.mainloop()
I tried with a ball ad it's work, but I don't know why, it doesn't with the logo.
You need to put the image using canvas.create_image() and then you can move the image using canvas.move().
from tkinter import *
from PIL import ImageTk, Image
fen = Tk()
fen.title('AllTech - Bouncing ball')
fen.resizable(False, False)
WIDTH, HEIGHT = 400, 300
canvas = Canvas(fen, width=WIDTH, height=HEIGHT, bg="white")
canvas.pack()
img = ImageTk.PhotoImage(Image.open("dvd.gif"))
# put the image into canvas
logo = canvas.create_image(0, 0, image=img, anchor="nw")
xspeed = yspeed = 3
def moveLogo():
global xspeed, yspeed
# move the image
canvas.move(logo, xspeed, yspeed)
# get bounding box of the image
(leftPos, topPos, rightPos, bottomPos) = canvas.bbox(logo)
if leftPos <= 0 or rightPos >= WIDTH:
xspeed = -xspeed
if topPos <= 0 or bottomPos >= HEIGHT:
yspeed = -yspeed
canvas.after(30, moveLogo)
canvas.after(30, moveLogo)
fen.mainloop()

Can I set an exact location of an object using tkinter?

Using Python3.7 I have created code that will move a ball from the top left corner to the bottom right corner. I am using coords to position the ball and move for the motion of the ball. However, I want the ball to start in a certin place. How can I set the position of the ball?
I have tried using place function and I get the error: 'int' object has no attribute 'place'
I tried using coords and I get the error: IndexError: list index out of range
I have tried changing my create_oval code. It works for the size of the ball but not where it starts from.
The code here works with no errors. How and where should I have a line for the exact coordinates of where the ball will start.
import tkinter as tkr
import time
tk = tkr.Tk()
canvas = tkr.Canvas(tk, width=480, height=480)
canvas.grid()
ball = canvas.create_oval(10,10,20,20,fill="blue")
x = 1
y = 1
while True:
canvas.move(ball,x,y)
pos = canvas.coords(ball)
if pos [3] >= 480 or pos[1] <=0:
y = -y
if pos[2] >= 480 or pos[0] <= 0:
x = -x
tk.update()
time.sleep(0.0099)
pass
tk.mainloop()
Also if I can get rid of the deprecation warning, that would be great as well.
Here's how you do a loop like this within the confines of an event-driven UI framework. Each callback does one little bit of work, then goes back to the loop to wait for future events.
import tkinter as tk
import time
win = tk.Tk()
canvas = tk.Canvas(win, width=480, height=480)
canvas.grid()
x = 10
y = 10
dx = 1
dy = 1
def moveball():
global x, dx
global y, dy
x += dx
y += dy
canvas.move(ball,dx,dy)
if y >= 480 or y <=0:
dy = -dy
if x >= 480 or x <= 0:
dx = -dx
win.after( 10, moveball )
ball = canvas.create_oval(x,y,x+10,y+10,fill="blue")
win.after( 100, moveball )
win.mainloop()
You'll note that the ball doesn't change directions until after it's all the way off the edge of the screen. That's because we're tracking the upper left corner of the ball and not taking the size into account. That's an easy thing to fix.
Used variables with the create_oval.
import tkinter as tkr
import time
tk = tkr.Tk()
canvas = tkr.Canvas(tk, width=480, height=480)
canvas.grid()
x = 47
y = 185
ball = canvas.create_oval(x,y,x+10,y+10,fill="blue")
dx = 1
dy = 1
while True:
canvas.move(ball,dx,dy)
pos = canvas.coords(ball)
if pos [3] >= 480 or pos[1] <=0:
dy = -dy
if pos[2] >= 480 or pos[0] <= 0:
dx = -dx
tk.update()
time.sleep(0.0099)
pass
tk.mainloop()
Big thanks to Tim Roberts. I end up taking his coding advice and edit mine original code.

How can I add collisions to a list of objects (circles) in tkinter?

import time
from tkinter import *
import random
class SpaceField:
def __init__(self):
self.window = Tk()
self.window.title("Asteriods")
self.canvas = self.canvas_display() #creates canvas
self.asteriods = self.asteriod_creation_seperation() #creates asteroids
self.active = True
self.move_active() #Moves asteroids
self.canvas.update()
def asteriod_creation_seperation(self): #creation of multple asteriods
asteriod_spacingx = random.randint(1,800)
asteriod_spacingy = random.randint(1,800)
asteriod_list = list() # could list([])
for i in range(15):
asteriod = self.canvas.create_oval( 30, 50 , 80 , 100 , tags="asteriod", width=2, outline="white")
asteriod_list.append("asteriod")
self.canvas.move(asteriod, asteriod_spacingx, asteriod_spacingy)
asteriod_spacingx = random.randint(1,500)
asteriod_spacingy = random.randint(1,500)
print(asteriod_spacingy)
return asteriod_list
Asteroid Creation. Creates asteroids and gives them random positions.
def asteriod_update(self): #asteriods movement method #MAin problem
x12 = 1
self.canvas.move("asteriod", 3, x12)
pos = self.canvas.coords("asteriod")
print(pos)
if (pos)[2] > 500:
x12 *= 5
I think this is where I need to add the collision detection. I just have no idea how to combine the lists of the circles and the collisions.
def move_active(self): #Basically a true loop
if self.active:
self.asteriod_update()
self.window.after(40, self.move_active)
def canvas_display(self): #canvas
canvas = Canvas(self.window, width=500, height=400, background='black')
canvas.pack(expand=True, fill="both")
canvas.update()
return canvas
Canvas display nothing special
def run(self):
self.window.mainloop()
if __name__ == '__main__':
SpaceF = SpaceField()
SpaceF.run()
Asteroids is a classic game but there were a number of problems in your code. The main one was calling move_active during initialization. This prevented the code from completing its mainloop initialization.
The other problem was the asteroid_update method that basically didn't do anything, also using tags to control all asteroids didn't work either.
Everything else was OK, although you might consider using polygons.
Here is one way to produce a bouncing objects program. I've inserted remarks that describe the methods used.
Objects change the speed and direction when they hit the boundary so their trajectories are randomized.
from tkinter import *
from random import randint as rnd
class SpaceField:
def __init__(self):
self.window = Tk()
self.window.title("Asteriods")
# Define canvas size and active flag
self.wide, self.high, self.active = 500, 400, True
self.canvas_display()
self.asteriod_creation_seperation()
def asteriod_creation_seperation(self):
self.asteroids, self.speed = [], []
size, radius = 50, 25
for i in range(15):
spacex = rnd(size, self.wide - size)
spacey = rnd(size, self.high - size)
self.asteroids.append( # Store oval item id
self.canvas.create_oval(
spacex, spacey, spacex+size, spacey+size,
width=2, tags = "asteriod", outline = "white"))
self.speed.append((rnd(1,4),rnd(1,4))) # Store random speed x, y
def asteriod_update(self): # MAIN DRIVER: Work on ALL asteroids
for i, a in enumerate(self.asteroids):
xx, yy = self.speed[i] # get speed data
x, y, w, h = self.canvas.coords(a)
# check for boundary hit then change direction and speed
if x < 0 or w > self.wide:
xx = -xx * rnd(1, 4)
if y < 0 or h > self.high:
yy = -yy * rnd(1, 4)
# Limit max and min speed then store it
self.speed[i] = (max( -4, min( xx, 4)), max( -4, min( yy, 4 )))
self.canvas.move(a, xx, yy) # update asteroid position
def move_active(self):
if self.active:
self.asteriod_update()
self.window.after(40, self.move_active)
def canvas_display(self):
self.canvas = Canvas(
self.window, width = self.wide,
height = self.high, background = "black")
self.canvas.pack(expand = True, fill = "both")
def run(self): # Begin asteroids here so that mainloop is executed
self.window.after(200, self.move_active)
self.window.mainloop()
if __name__ == "__main__":
SpaceF = SpaceField()
SpaceF.run()

python tkinter bouncing ball game

I'm making a basic game. I want the ball to bounce back up ONLY when it hits the platform. So far, I've written code that will make the ball bounce off the top and bottom screen, but I'm having trouble with getting the ball to bounce off the platform.
from tkinter import *
import time
import tkinter
tk = Tk()
canvas = Canvas(tk, bg="white",width=(900),height=(500))
canvas.pack()
platform = canvas.create_rectangle(400,400,500,410)
def ball():
xspeed = 2
yspeed = 2
ball = canvas.create_oval(430,10,470,50)
while True:
canvas.move(ball, xspeed, yspeed)
pos = canvas.coords(ball)
if pos[2] >=900 or pos[0] <0:
xspeed = -xspeed
tk.update()
time.sleep(0.01)
def board():
board_right()
board_left()
def board_right(event):
xspeed = 5
yspeed = 0
canvas.move(platform,xspeed,yspeed)
tk.update
time.sleep(0.01)
def board_left(event):
xspeed = 5
yspeed = 0
canvas.move(platform,-xspeed,yspeed)
tk.update()
time.sleep(0.01)
canvas.bind_all("<Right>",board_right)
canvas.bind_all("<Left>",board_left)
ball()
tk.mainloop()
Do not use time.sleep() as it will block the tkinter mainloop, use after() instead.
To check whether the ball hits the platform, you need to get the center x of the ball and the lower y of the ball. If center x is within the left and right of platform and the ball lower y is the platform upper y, then reverse the ball y speed. Otherwise game over!
Below is sample code based on yours:
import tkinter as tk
root = tk.Tk()
width = 900
height = 500
canvas = tk.Canvas(root, bg='white', width=width, height=height)
canvas.pack()
ball = canvas.create_oval(430, 10, 470, 50, fill='green')
platform_y = height - 20
platform = canvas.create_rectangle(width//2-50, platform_y, width//2+50, platform_y+10, fill='black')
# ball moving speed
xspeed = yspeed = 2
def move_ball():
global xspeed, yspeed
x1, y1, x2, y2 = canvas.coords(ball)
if x1 <= 0 or x2 >= width:
# hit wall, reverse x speed
xspeed = -xspeed
if y1 <= 0:
# hit top wall
yspeed = 2
elif y2 >= platform_y:
# calculate center x of the ball
cx = (x1 + x2) // 2
# check whether platform is hit
px1, _, px2, _ = canvas.coords(platform)
if px1 <= cx <= px2:
yspeed = -2
else:
canvas.create_text(width//2, height//2, text='Game Over', font=('Arial Bold', 32), fill='red')
return
canvas.move(ball, xspeed, yspeed)
canvas.after(20, move_ball)
def board_right(event):
x1, y1, x2, y2 = canvas.coords(platform)
# make sure the platform is not moved beyond right wall
if x2 < width:
dx = min(width-x2, 10)
canvas.move(platform, dx, 0)
def board_left(event):
x1, y1, x2, y2 = canvas.coords(platform)
# make sure the platform is not moved beyond left wall
if x1 > 0:
dx = min(x1, 10)
canvas.move(platform, -dx, 0)
canvas.bind_all('<Right>', board_right)
canvas.bind_all('<Left>', board_left)
move_ball()
root.mainloop()

How do I have an object rebound off the canvas border?

I am using the canvas widget from tkinter to create an ellipse and have it move around in the canvas.
However when the ellipse comes in contact with the border it gets stuck to wall instead of bouncing off.
I'm struggling with debugging the code, thanks in advance!
from tkinter import *
from time import *
import numpy as np
root = Tk()
root.wm_title("Bouncing Ball")
canvas = Canvas(root, width=400, height=400, bg="black")
canvas.grid()
size=10
x = 50
y = 50
myBall = canvas.create_oval(x-size, y-size, x+size, y+size, fill = "red")
while True:
root.update()
root.after(50)
dx = 5
dy = 0
#separating x and y cooridnates from tuple of canvas.coords
x = canvas.coords(myBall)[0]+10
y = canvas.coords(myBall)[1]+10
coordinates = np.array([x, y], dtype = int)
#Checking boundaries
if coordinates[0]-size <= 0:
dx = -1*dx
if coordinates[0]+size >= 400:
dx = -1*dx
if coordinates[1]-size <= 0:
dy = -1*dy
if coordinates[1]+size >= 400:
dy = -1*dy
print(coordinates) #Used to see what coordinates are doing
canvas.move(myBall, dx, dy) #Move ball by dx and dy
Here is a simple way to organize your bouncing ball program, and get you started with GUI programming:
While loops don't work well with a GUI mainloop; it is also not necessary to call update, the mainloop handles that.
Repeated actions are best handles with root.after.
I extracted the bounce logic inside a function bounce that calls itself using root.after. You will see that I simplified the logic.
I also parametrized the canvas size.
The initial speed components dx and dy are randomly chosen from a list of possible values so the game is not too boring.
Here is how it looks:
import tkinter as tk # <-- avoid star imports
import numpy as np
import random
WIDTH = 400
HEIGHT = 400
initial_speeds = [-6, -5, -4, 4, 5, 6]
dx, dy = 0, 0
while dx == dy:
dx, dy = random.choice(initial_speeds), random.choice(initial_speeds)
def bounce():
global dx, dy
x0, y0, x1, y1 = canvas.coords(my_ball)
if x0 <= 0 or x1 >= WIDTH: # compare to left of ball bounding box on the left wall, and to the right on the right wall
dx = -dx
if y0 <= 0 or y1 >= HEIGHT: # same for top and bottom walls
dy = -dy
canvas.move(my_ball, dx, dy)
root.after(50, bounce)
if __name__ == '__main__':
root = tk.Tk()
root.wm_title("Bouncing Ball")
canvas = tk.Canvas(root, width=400, height=400, bg="black")
canvas.pack(expand=True, fill=tk.BOTH)
size=10
x = 50
y = 50
my_ball = canvas.create_oval(x-size, y-size, x+size, y+size, fill="red")
bounce()
root.mainloop()
It's just basic math. The ball moves left when you subtract some amount from the x coordinate. If it hits the left wall and you want it to bounce to the right, you need to stop subtracting from x and start adding to x. The same is true for the y coordinate.

Categories

Resources