I want this def function to repeat itself as soon as the ball hits the ground (border of the window) I tried using if , for loop and while: , but I wasn't able to make it work. I'm a beginner so maybe I'm just making stupid mistakes. Thanks for the help.
import tkinter
canvas = tkinter.Canvas(width=600, height=600)
canvas.pack()
def ball():
canvas.delete('all')
global y
canvas.create_oval(x - 5,y - 5,x + 5,y + 5, fill = 'red')
y = y + 2
if y < 600:
canvas.after(2, ball)
y = 0
x=300
ball()
TL;DR : I want to repeat a def function in Python after a certain event.
I implement a situation with python to show you how you can use the while
loop and also using return
for your functions to exit the loop after some event. It's just an example for better understanding the answer. And do not use global variables in your code. It's just for the example.
a = 100
def count_down():
global a
a -= 1
if a > 0:
return True
return False
in_the_loop = True
while(in_the_loop):
in_the_loop = count_down()
print(a)
Maybe this snippet will give some idea about your case to how to exit from the base
function by simply adding return
to that.
It sounds like you just want to reset the y
value:
import tkinter
canvas = tkinter.Canvas(width=600, height=600)
canvas.pack()
def ball():
canvas.delete('all')
global y
canvas.create_oval(x - 5,y - 5,x + 5,y + 5, fill = 'red')
y = y + 2
if y >= 600:
y = 0 # Restart y from 0 again
canvas.after(2, ball)
y = 0
x=300
ball()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.