Call back in Python

Can someone explain how callback methods work, and if possible give me an example in Python? As far as I understand, they are methods provided by the user API, API, so the user does not need to wait for the completion of this specific API function. So does the user program continue, and as soon as the callback method is called by the API, return to the point in the program where the callback method was provided? How does the callback method significantly affect the program flow?

Sorry if I'm blurry here.

+4
source share
1 answer

Callbacks are just user hooks. They allow you to specify which function to call in case of certain events. re.sub has a callback, but it looks like you are dealing with a GUI, so I will give an example GUI:

Here is a very simple callback example:

 from Tkinter import * master = Tk() def my_callback(): print('Running my_callback') b = Button(master, text="OK", command=my_callback) b.pack() mainloop() 

When you click OK , the program prints "Launch my_callback".

If you play with this code:

 from Tkinter import * import time master = Tk() def my_callback(): print('Starting my_callback') time.sleep(5) print('Ending my_callback') def my_callback2(): print('Starting my_callback2') time.sleep(5) print('Ending my_callback2') b = Button(master, text="OK", command=my_callback) b.pack() b = Button(master, text="OK2", command=my_callback2) b.pack() mainloop() 

You will see that pressing any button blocks the display of the graphical user interface until the callback is completed. User thus must wait until this particular API function completes. "

+7
source

Source: https://habr.com/ru/post/1315815/


All Articles