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

2024/11/19 5:35:39

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 = 5dy = 0
#separating x and y cooridnates from tuple of canvas.coordsx = canvas.coords(myBall)[0]+10y = canvas.coords(myBall)[1]+10coordinates = np.array([x, y], dtype = int)
#Checking boundariesif coordinates[0]-size <= 0:dx = -1*dxif coordinates[0]+size >= 400:dx = -1*dxif coordinates[1]-size <= 0:dy = -1*dyif coordinates[1]+size >= 400:dy = -1*dyprint(coordinates) #Used to see what coordinates are doingcanvas.move(myBall, dx, dy) #Move ball by dx and dy
Answer

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 randomWIDTH = 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, dyx0, 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 walldx = -dxif y0 <= 0 or y1 >= HEIGHT:   # same for top and bottom wallsdy = -dycanvas.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=10x = 50y = 50my_ball = canvas.create_oval(x-size, y-size, x+size, y+size, fill="red")bounce()root.mainloop()
https://en.xdnf.cn/q/118578.html

Related Q&A

How to scrape data using next button with ellipsis using Scrapy

I need to continuously get the data on next button <1 2 3 ... 5> but theres no provided href link in the source also theres also elipsis. any idea please? heres my codedef start_requests(self):u…

Execution Code Tracking - How to know which code has been executed in project?

Let say that I have open source project from which I would like to borrow some functionality. Can I get some sort of report generated during execution and/or interaction of this project? Report should…

Python code to ignore errors

I have a code that stops running each time there is an error. Is there a way to add a code to the script which will ignore all errors and keep running the script until completion?Below is the code:imp…

How to match background color of an image with background color of Pygame? [duplicate]

This question already has an answer here:How to convert the background color of image to match the color of Pygame window?(1 answer)Closed 3 years ago.I need to Make a class that draws the character a…

Sharepoint/SOAP - GetListItems ignoring query

Trying to talk from Python to Sharepoint through SOAP.One of the lists I am trying to query contains ID as primary key field.(Field){_RowOrdinal = "0"_FromBaseType = "TRUE"_DisplayN…

python mean between file

I create a list of more than a thousand file (Basically now I have a list with the name of the file) now in order to make the man I thought to do something like this (suppose asch file have 20 lines): …

Sort a dictionary with custom sorting function

I have some JSON data I read from a file using json.load(data_file){"unused_account":{"logins": 0,"date_added": 150},"unused_account2":{"logins": 0,&qu…

Turtle make triangle different color

Hi guys Im trying to replicate this image:Its almost done I just have one issue, where the triangle is supposed to be yellow it isnt seeming to work.Mine:Code:fill(True) fillcolor(green) width(3) forwa…

How to DataBricks read Delta tables based on incremental data

we have to read the data from delta table and then we are joining the all the tables based on our requirements, then we would have to call the our internal APIS to pass the each row data. this is our g…

Converting an excel file to a specific Json in python using openpyxl library with datetime

I have the Excel data with the format shown in the image preview. How can I convert it into a JSON using Python? Expected Output: file_name = [ { A: Measurement( calculated_date=datetime(2022, 10, 1, …